资料内容:
2.3 Read and Write Reading and writing information from data files, be it in text or binary format, is crucial for scientific computing. It provides the ability to save, share, and read data that is computed by any language. Fortunately, Python is quite capable of reading and writing data. 2.3.1 Text Files In terms of text files, Python is one of the most capable programming languages. Not only is the parsing robust and flexible, but it is also fast compared to other languages like C. Here’s an example of how Python opens and parses text information. # Opening the text file with the 'r' option, # which only allows reading capability f = open('somefile.txt', 'r') # Parsing the file and splitting each line, # which creates a list where each element of # it is one line alist = f.readlines() # Closing file f.close() . . . # After a few operations, we open a new text file # to write the data with the 'w' option. If there # was data already existing in the file, it will be overwritten. f = open('newtextfile.txt', 'w') # Writing data to file f.writelines(newdata) # Closing file f.close() Accessing and recording data this way can be very flexible and fast, but there is one downside: if the file is large, then accessing or modulating the data will be cumbersome and slow. Getting the data directly into a numpy.ndarray would be the best option. We can do this by using a NumPy function called loadtxt. If the data is structured with rows and columns, then the loadtxt command will work very well as long as all the data is of a similar type, i.e., integers or floats. We can save the data through numpy.savetxt as easily and quickly as with numpy.readtxt. import numpy as np arr = np.loadtxt('somefile.txt') np.savetxt('somenewfile.txt') If each column is different in terms of formatting, loadtxt can still read the data, but the column types need to be predefined. The final construct from reading the data will 12 | Chapter 2: NumPy 9781449305468_text.pdf 20 10/31/12 2:35 PM be a recarray. Here we run through a simple example to get an idea of how NumPy deals with this more complex data structure. # example.txt file looks like the following # # XR21 32.789 1 # XR22 33.091 2 table = np.loadtxt('example.txt', dtype='names': ('ID', 'Result', 'Type'), 'formats': ('S4', 'f4', 'i2')) # array([('XR21', 32.78900146484375, 1), # ('XR22', 33.090999603271484, 2)], # dtype=[('ID', '|S4'), ('Result', '