python乱炖.3——file文件操作

python.3——file文件操作



#各种操作

open() 函数接收两个参数:文件名(file)和模式(mode)。
open(file, mode=‘r’)
如果文件不在当前工作目录下,需要提供文件的完整路径。

这四种最常用

模式操作
x写模式,新建一个文件,如果该文件已存在则会报错。
r以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
a追加内容
w打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。

open and read

#打开文件 example.txt,模式为只读
file = open("example.txt", "r")
#read(): 读取整个文件内容
content = file.read()  ///这里read(5)里如果有值,就是读取部分内容
print(content)
#readline(): 逐行读取文件内容,一次读取一行。
line = file.readline()
print(line)

# 打开文件并读取内容
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  • with 语句确保文件在使用后会自动关闭,即使发生错误

write

#write(): 向文件写入字符串
file.write("Hello, World!")

#writelines(): 写入一个字符串列表,每个字符串作为文件的一行
lines = ["First line\n", "Second line\n", "Third line\n"]
file.writelines(lines)

# 写入内容到文件
with open("example.txt", "w") as file:
    file.write("Hello, World!")
  • 如果文件 example.txt 不存在,它将被创建。如果文件已经存在,内容将被覆盖。
# 追加内容到文件末尾
with open("example.txt", "a") as file:
    file.write("\nThis is an additional line.")
    
# 逐行读取文件
with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())
#关闭文件
file.close()

delete

import os
os.remove("demofile.txt")

#检查是否存在再删除
import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")
```
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值