1. Open the file
Open the file with handle=open(filename,mode). This function will return a handle (should be translated as "handle") to manipulate the file, the parameter filename is a string. The parameter mode is optional, 'r' stands for read file, 'w' stands for write file.
example:
>>> fhand=open('mbox.txt','r')
>>> print(fhand)
<_io.TextIOWrapper name='mbox.txt' mode='r' encoding='UTF-8'>
The file handle can be regarded as a sequence of strings, and each line of the file example is the content of this sequence of strings.
Example: Counting the number of lines in the file content
fhand=open('mbox.txt') count=0 for line in fhand: count=count+1 print('Line Count:',count) $ python open.py Line Count:132045
Example: Retrieving file content
fhand = open(;mbox-short.txt') for line in fhand: if line.startswith('From:'): print(line)
2. Read the file
Use read() to read the entire file (including newlines, etc.) into a single string.
example:
>>> fhand=open('mbox-short.txt') >>> inp=fhand.read() >>> print(len(inp)) 94626 >>> print(inp[:20]) From stephen.marquar