Python-文件

python-文件

文件操作:

文件读取文件写入追加内容

文件读取:
以 open(‘logs.txt’, ‘r’) 作为文件:

openpython内置函数,用于打开文件。第一个参数是文件名,第二个参数是读取模式。
with语句用于自动关闭文件。这将防止内存泄漏,提供更好的资源管理
as file as 关键字将打开的文件对象分配给变量 file

with open('logs.txt', 'r')as file:    # print(file, type(file))    content = file.readlines()    print(content, type(content))   # this content is a list. elements are each line in file     for line in content:        print(line, end='') # end='' is defined to avoid n as list iteration ends already with n        #print(line.strip())

输出:
[‘这是用于存储日志的文件’, ‘创建于 12.08.2024n’, ‘作者 suresh sundararajun’]
这是用来存储日志的文件
创建于 12.08.2024
作者 suresh sundararaju

file.readlines() 将以列表形式给出文件内容

file.readline() 会将第一行作为字符串给出

迭代列表,每一行都可以作为字符串检索

迭代后面,每个str都可以作为字符检索

立即学习“Python免费学习笔记(深入)”;

这里当通过for循环迭代列表时,返回以换行符结束。当用打印语句打印时,又出现了另一行。为了避免使用 strip() 或 end=”

文件写入:
以 open(‘notes.txt’,’w’) 作为文件:

这和文件读取类似。唯一的语法差异是模式被指定为“w”。这里将创建notes.txt文件。

进一步写入内容,我们可以使用 file.write(‘content’)
使用写入模式,每次都会创建文件并且内容将在该块内被覆盖

# write in filewith open('notes.txt', 'w') as file:    i=file.write('1. file createdn')    i=file.write('2. file updatedn')

附加在文件中:
以 open(‘notes.txt’, ‘a’) 作为文件:

对于追加,mode=’a’ 与 file.write(str) 或 file.writelines(list) 一起使用。这里现有的文件中,最后会更新内容。

#Append filewith open('notes.txt', 'a') as file:    file.write('Content appendedn')#Read all the lines and store in listwith open('notes.txt', 'r') as file:    appendcontent = file.readlines()    print(appendcontent)

输出:
[‘1.文件已创建n’, ‘2.文件已更新’, ‘内容已追加’]

备注:

还有一些其他模式可用 ‘r+’,’w+’,’a+’可以添加例外

以上就是Python-文件的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1348926.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 12:26:44
下一篇 2025年12月13日 12:27:01

相关推荐

发表回复

登录后才能评论
关注微信