文件读写比较简单,这里就是起一个mark的作用。突出read 和readlines的区别。后者读到一个list中,前者直接读到全部内容。区别还是看一个demo:
outfile = open("lxyfiledemo.txt","w")
outfile.write("hello,this is just a test for writing file in python")
outfile.write("\n")
outfile.write("hi over")
outfile.close()
infile = open("lxyfiledemo.txt")
content = infile.read()
infile.close()
print(content)
infile2 = open("lxyfiledemo.txt")
infile2.seek(0)
infile2contentList = infile2.readlines()
infile2.close()
print(infile2contentList)
输出为:
hello,this is just a test for writing file in python
hi over
['hello,this is just a test for writing file in python\n', 'hi over']
说明:以上结果可以看到,read读到全部内容然后输出。
readlines读进一个list然后打印这个list.
本文通过一个简单的示例对比了Python中使用read()和readlines()方法读取文件的区别。read()将文件内容作为字符串一次性读取,而readlines()则会将文件内容按行读取并存储为列表。
437

被折叠的 条评论
为什么被折叠?



