Files can be opened by calling open or file. open is generally more common than file, because file is almost all tailored for object-oriented programming.
URL: http://www.cnblogs.com/archimedes/p/python-file.html.
Open a file
When you open a file program, it calls the built-in open function. The first is the external name, and then the processing mode.
Common file operations:
In any case, the text file in the Python program is in the form of a string. when reading the text, the text in the form of a string is returned.
The data read from the file is returned to the script as a string, so if the string is not what you need, you have to convert it to another type of Python object.
Files in actual application
First, let's look at a simple example of File Processing:
>>> myfile=open('myfile','w')>>> myfile.write('hello,myfile!\n')>>> myfile.close()>>> myfile=open('myfile')>>> myfile.readline()'hello,myfile!\n'>>> myfile.readline()''
Write a line of text into a string containing the line terminator \ n. The writing method does not add a line terminator to us.
Store and parse Python objects in files
You must use the Conversion Tool to convert an object to a string. Note that the file data must be a string in the script, and the writing method does not automatically convert the object to the string format.
>>> X,Y,Z=43,324,34>>> S='Spam'>>> D={'a':1,'b':2}>>> L=[1,2,3]>>> F=open('datafile.txt','w')>>> F.write(S+'\n')>>> F.write('%s,%s,%s\n'%(X,Y,Z))>>> F.write(str(L)+'$'+str(D)+'\n')>>> F.close()
Once a file is created, you can open and read strings to view the content of the file. The print statement will explain the embedded line terminator to the user's satisfaction:
>>> bytes=open('datafile.txt').read()>>> bytes"Spam\n43,324,34\n[1, 2, 3]${'a': 1, 'b': 2}\n">>> print bytesSpam43,324,34[1, 2, 3]${'a': 1, 'b': 2}
Since Python does not automatically convert strings to numbers or other types of objects, Common Object tools such as indexing and addition are required.
>>> F=open('datafile.txt')>>> line=F.readline()>>> line'Spam\n'>>> line=F.readline()>>> line'43,324,34\n'>>> parts=line.split(',')>>> parts['43', '324', '34\n']>>> int(parts[1])324>>> numbers=[int(p) for p in parts]>>> numbers[43, 324, 34]>>> line=F.readline()>>> line"[1, 2, 3]${'a': 1, 'b': 2}\n">>> parts=line.split('$')>>> parts['[1, 2, 3]', "{'a': 1, 'b': 2}\n"]>>> eval(parts[0])[1, 2, 3]>>> objects=[eval(p) for p in parts]>>> objects[[1, 2, 3], {'a': 1, 'b': 2}]Use pickle to store Python native objects
Eval can be used to convert a string to an object. The pickle module is an advanced tool that allows us to directly store almost any Python object in a file. It does not require String Conversion.
>>> F=open('datafile.txt','w')>>> import pickle>>> pickle.dump(D,F)>>> F.close()>>> F=open('datafile.txt')>>> E=pickle.load(F)>>> E{'a': 1, 'b': 2}
The pickle module implements Object serialization, that is, mutual conversion between objects and byte strings.