To open a file:
open(filename, mode)
mode:
‘r’ to open for reading
'w' to open for writing
'a' to open for appending(adding to what is already in the file)
>>> file = 'C:\\Users\document.txt' 双斜杠避免被解释为转义字符
>>> filename = open(file, 'r')
>>> line = filename.readline()
>>> while line != '':
print(line)
line = filename.readline()
>>> filename.close()
when you want to process every line in a file use the for line in file approach:
for line in file:
process line
file.read(): print the whole document as a string
list = file.readlines():自动将文件分析成一个行的列表,这个列表可由python的for...in...进行处理 如,for line in file.readlines()
readline():read and return the next line from the file, including the newline character(if it exists)
return the empty string if there are no more lines in the file,每次只读取一行