1. Open File
Use Handle=open (Filename,mode) to open the file. This function will return a handle (which should be translated as "handle") to manipulate the file, and the parameter filename is a string. The parameter mode is optional, ' R ' stands for reading the file, ' W ' represents the Write file.
Cases:
>>> Fhand=open ('mbox.txt','r')
>>> Print (Fhand)
<_io. Textiowrapper name= ' mbox.txt ' mode= ' r ' encoding= ' UTF-8 ' >
The file handle can be thought of as a sequence of strings, and each line of an instance of the document is the contents of the string sequence.
Example: Number of rows of file contents
Fhand=open ('mbox.txt') Count=0 for in Fhand: count=count+1print('linecount:', count) $ python Open.pyline Count:132045
Example: Retrieving the contents of a file
Fhand = open (; mbox-short.txt') for in fhand: if Line.startswith ('from:'): print(line)
2. Read the file
Use Read () to read the entire file (including line breaks, etc.) and deposit a separate string.
Cases:
>>> Fhand=open ('mbox-short.txt')>>> inp=fhand.read () Print(len (INP))print(inp[:20]) from Stephen.marquar
"Python study notes" Coursera's py4e study notes--file