python:一行代码读写文件

发布时间 2023-06-27 11:30:20作者: nxhujiee

1、读取文件

lst = [line.strip() for line in open('data.txt')]
print(lst)

这里我们使用列表来处理。

首先,我们打开一个文本文件,并使用for循环,逐行读取。 最后,使用strip删除所有不必要的空间。

通过使用列表功能,使得代码更简单,更短。

list(open('data.txt'))

##Using with will also close the file after use
with open("data.txt") as f:
    lst=[line.strip() for line in f]
print(lst)

2、将数据写入文件

with open("data.txt",'a',newline='\n') as f: 
    f.write("Python is awsome")

上面的代码首先创建一个文件data.txt(如果没有的话),然后它会在文件中写Python is awesome。