python如何在文件最后一行前面加上特定字符

python如何在文件最后一行前面加上特定字符,第1张

filename="文件名"

result=[]

for f in open(filename):

    result.append(f)

result[-1]='c'+result[-1]

open(filename,'w').writelines(result)

将文件最后一行前加上字符 c

1.提高程序的可维护性和易读性,小的项目可能你还不能体会模块化编程的好处,当你在一个团队中做较大的项目时,你什么都写在一个文件里,在你还没到后期维护之时吐槽自己的做法前,估计你的同事和产品经理就在你第一次上传代码时集体爆你jh了,详细的东西你可以百度下模块编程的好处。

2.在主程序内导入了这些模块,主程序即可使用这些模块的功能。

def read_file(file_path="abc.txt"):

file = open(file_path, "r")

content = file.readlines()

file.close()

return content

def write_file(content, file_path="abc1.txt"):

file = open(file_path, "w")

file.writelines(content)

file.flush()

file.close()

if __name__ == "__main__":

content = read_file()

new_content = list()

for c in content:

c = c.strip()

new_content.append(c + str(int(c) - 1) + "\r\n")

write_file(new_content)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11926188.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存