打开文件
f=open('test.txt','rt')
g=open('test.txt','wt')
读取所有内容
data=f.read()
data=f.read([maxbytes])
写入内容
g.write('hello world')
关闭文件
f.close()
g.close()
文件应当在使用完毕后关闭,否则会导致内存泄漏。使用 with 语句可以自动关闭文件。
离开 with 语句后,文件会自动关闭。
with open(filename, 'rt') as file:
# Use the file `file`
...
# No need to close explicitly
...statements
使用with
语句读取挣个文件
with open('foo.txt', 'rt') as file:
data = file.read()
使用with
语句按行读取文件
with open('foo.txt', 'rt') as file:
for line in file:
使用with
语句写入文件
with open('outfile', 'wt') as out:
out.write('Hello World\n')
重定向print
函数
with open('foo.txt', 'wt') as file:
print('hello world', file=file)