Python 将页眉和页脚添加到文件中的每一行。函数只返回第一行
我的一些python代码有问题。我希望它打开一个文件,有几行文字,并添加页眉+页脚到该文件中的每一行。 问题是“create_output”函数只返回包含附加内容的第一行。如果在该函数结束时将“return”切换为“print”,则会正确显示文件中的所有行。原因可能是什么?我想知道我做错了什么Python 将页眉和页脚添加到文件中的每一行。函数只返回第一行,python,python-2.7,Python,Python 2.7,我的一些python代码有问题。我希望它打开一个文件,有几行文字,并添加页眉+页脚到该文件中的每一行。 问题是“create_output”函数只返回包含附加内容的第一行。如果在该函数结束时将“return”切换为“print”,则会正确显示文件中的所有行。原因可能是什么?我想知道我做错了什么 file_path = '/home/user/Desktop/text.txt' file_path_edited = '/home/user/Desktop/text_new.txt' header
file_path = '/home/user/Desktop/text.txt'
file_path_edited = '/home/user/Desktop/text_new.txt'
header = 'http://'
footer = '.com'
def open_file():
opened_file = open(file_path)
return opened_file
def edit_file():
edited_file = open(file_path_edited, 'w')
return edited_file
def create_output():
for line in open_file():
line = line.strip()
edited_line = header+line+footer
to_file = edit_file()
to_file.writelines(edited_line)
to_file.close()
return edited_line
print (create_output())
您只得到一行,因为您一直都在重新打开写文件,而不是让它打开,所以w将在打开时截断文件-因此最后一行仍然有效,其余的是无用的IO。此外,你永远不会关闭你的读者afaics openfilename,模式来自: 仅读取文件时,模式可以为“r”,仅写入具有相同名称的现有文件时的“w”将被擦除,“a”将打开文件进行附加;写入文件的任何数据都会自动添加到末尾。”r+'打开文件进行读取和写入。mode参数是可选的;'如果省略,则假定为r’ 不要将打开的文件拆分为其他函数,请与open。。。作为布拉:布拉。写。。。因此,一旦你离开街区或发生异常情况,它们就会关闭 使用字符串格式-可以是“this{}ist repleached with.”formatsomething或内联变量-请参见下文
def create_output():
modLines = []
with open('/home/user/Desktop/text.txt',"r") as reader, \
open('/home/user/Desktop/text_new.txt',"w") as writer:
for line in reader:
line = line.strip().rstrip('\n') # rstrip might be better if you only cut \n
modline = f'http://{line}.com' # 3.6 inline string formatting, for 2.7 use
modLines.append(modline) # 'http://{}.com'.format(line)
writer.write(modline+"\n") # write does not autoappend \n
return modlines # return a list of written https...
print (create_output())
我们应该做到这一点
链接:
好的,我把它改成这样,现在它工作正常了。 谢谢你的反馈,现在我知道我做错了什么
file_path = '/home/user/Desktop/text.txt'
file_path_edited = '/home/user/Desktop/text_new.txt'
header = 'http://'
footer = '.com'
def CreateContent():
with open(file_path) as read_file:
with open(file_path_edited, 'w') as write_file:
for line in read_file.readlines():
new_line = "{}{}{}".format(header, line.strip(), footer)
print(new_line)
write_file.write("{}\n".format(new_line))
CreateContent()
您可以进一步改进代码,如下所示:
file_path = '/home/user/Desktop/text.txt'
file_path_edited = '/home/user/Desktop/text_new.txt'
header = 'http://'
footer = '.com'
def CreateContent():
with open(file_path) as read_file, open(file_path_edited, 'w') as write_file:
for line in read_file:
write_file.write("{}{}{}\n".format(header, line.strip(), footer))
CreateContent()
“创建内容”功能在哪里?抱歉,创建输出EdditedWhy您在创建输出循环中返回已编辑的\u行?因为已编辑的\u行就是输出?在你看来,我应该返回什么?如果你在循环中,它将在第一次迭代后退出函数…Thx很多!我重写了它,现在它运行良好。好吧,我需要更多更多的编码。@Oh亲爱的,太好了。请看这里: