python之读取与写入txt文件open()

学习文件过程中想尝试在py文件执行过程中将执行过程记录进自定义txt文件,先尝试能否打开非txt文件,大致的代码如下:

path = "源码.py"                  #需要读取的路径
filename = "a.txt"               #读取后的数据存放点(默认此程序同目录)
with open(path,'r') as line_object:   #'r'只读模式,'a'附加模式
     lines = line_object.headline()
for content in lines:
     with open(filename,'a') as file_object: 
         files = file_object.write(content+"\n")

报错:

Traceback (most recent call last):
  File "C:\Users\28654\Desktop\工算综合程序\kkk.py", line 6, in <module>
    lines = line_object.headline()
AttributeError: '_io.TextIOWrapper' object has no attribute 'headline'

因而选择尝试同txt文件操作:

pathfile = "a.txt"                 #需要读取的路径文件
filename = "b.txt"        #读取后的数据存放点(默认此程序同目录)
with open(pathfile,'r') as line_object:
    lines = line_object.headline()
for content in lines:
    with open(filename,'a') as file_object: 
        files = file_object.write(content+"\n")

a.txt , b.txt 以及该程序均保存在桌面,但出现无法找到的问题,希望有大佬能指点问题所在

Traceback (most recent call last):
  File "C:\Users\28654\Desktop\读取写入脚本.py", line 3, in <module>
    with open(pathfile,'r') as line_object:
FileNotFoundError: [Errno 2] No such file or directory: 'a.txt'
发布了2 篇原创文章 · 获赞 0 · 访问量 53

猜你喜欢

转载自blog.csdn.net/qq_45960624/article/details/104562619