本文最后更新于 258 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com
文件读写
写入测试文件:
%%writefile test.txt
this is a test file.
hello world!
python is good!
today is a good day.
Writing test.txt
读文件
使用 open()
函数来读文件,使用文件名的字符串作为输入参数:
f = open('test.txt')
可以使用 .read()
方法来读入文件中的所有内容:
text = f.read()
text
'this is a test file.\nhello world!\npython is good!\ntoday is a good day.\n'
print(text)
this is a test file.
hello world!
python is good!
today is a good day.
使用完文件之后,需要将文件关闭:
f.close()
也可以用.readlines()
方法按照行读入内容。该方法返回一个列表,每个元素代表文件中每一行的内容:
f = open('test.txt')
lines = f.readlines()
f.close()
print(lines)
['this is a test file.\n', 'hello world!\n', 'python is good!\n', 'today is a good day.\n']
还可以将f放入一个循环中,遍历:
f = open('test.txt')
for line in f:
print(line)
f.close()
this is a test file.
hello world!
python is good!
today is a good day.
删除演示文件:
%rm test.txt
写文件
写文件也使用open()
函数,只需要额外指定模式参数为w
:
f = open('myfile.txt', 'w')
f.write('hello world!')
f.close()
使用 w
模式时,如果文件不存在会被创建:
print(open('myfile.txt').read())
hello world!
如果文件存在,原先的内容会被完全覆盖:
f = open('myfile.txt', 'w')
f.write('another hello world!')
f.close()
print(open('myfile.txt').read())
another hello world!
如果不想覆盖,则需要使用追加模式a
:
f = open('myfile.txt', 'a')
f.write('... and more')
f.close()
print(open('myfile.txt').read())
another hello world!... and more
删除演示文件:
%rm myfile.txt