欢迎光临
我们一直在努力

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 file
with 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 file
with open('notes.txt', 'a') as file:
    file.write('Content appendedn')


#Read all the lines and store in list
with open('notes.txt', 'r') as file:
    appendcontent = file.readlines()
    print(appendcontent)

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

备注:

  1. 还有一些其他模式可用 ‘r+’,’w+’,’a+’
  2. 可以添加例外
赞(0) 打赏
未经允许不得转载:码农资源网 » Python-文件
分享到

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册