[重要] python:一行代码读写文件

python:一行代码读写文件

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。

posted @   nxhujiee  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示