python对文件的处理方法
2024-10-21 06:37:55
#1、打开文件 如果文件不存在会报错
file = open("1.txt") #2、使用w、w+、a、a+模式打开,如果文件不存在就创建文件
file = open("1.txt", "w") #3、指定绝对路径路径
file = open("D:\\1.txt", "w") #二进制模式打开图片或者视频
file = open("老虎头像.png", "rb")
print(file) #指定字符集打开文件
file = open("csv群聊.csv", "r", encoding='utf-8')
#关闭文件
file.close() #写入文件 复写
file = open("1.txt","w")
file.write("1111你好") #写入文件 追加
file = open("1.txt","a")
file.write("123123") # 打开文件 读取前9字符串
file = open("messages.txt", "r", encoding='utf-8')
string = file.read(9)
print(string) #想要从文件的第6个字符开始读取2个字符
file = open("messages.txt", "r", encoding='utf-8')
file.seek(5) # 移动指针到新的位置
string = file.read(2) # 读取2个字符
print(string) #读取一行
print("\n", "=" * 20, "Python经典应用", "=" * 20)
with open1("messages.txt", "r", encoding="utf-8") as file:
number = 0 # 记录行号
while True:
number += 1
line = file.readline()
if line == "":
break
print(number, line, end="\n")
print("\n ", "=" * 20, "over" * 20, "\n") #读取一行并将内容分割
print("\n", "=" * 20, "Python经典应用", "=" * 20)
with open2("csv群聊.csv", "r", encoding="utf-8") as file:
number = 0 # 记录行号
while True:
number += 1
line = file.readline() if line == "":
break
else:
print(number, line, end="\n")
lst = line.split(' ')#使用空字符串分割
for i in range(len(lst)):
print(i, lst[i]) print("\n ", "=" * 20, "over" * 20, "\n") #读取全部行 一次性输出
print("\n", "=" * 20, "Python经典应用", "=" * 20)
with open3("messages.txt", "r", encoding="utf-8") as file:
message = file.readlines() # 读取全部信息
print(message)
print("\n ", "=" * 20, "over", "=" * 20, "\n") # 读取全部行 将列表的内容逐行输出
print("\n", "=" * 20, "Python经典应用", "=" * 20)
with open4("messages.txt", "r", encoding="utf-8") as file:
messageall = file.readlines() # 读取全部信息
for message in messageall:
print(message) # 输出一条信息
print("\n ", "=" * 20, "over", "=" * 20, "\n")
最新文章
- 身份证验证合法性js--已验证
- 在OS X中使用Homebrew
- SQL Server2008函数大全(完整版)
- HTTP 头部
- Redis使用介绍
- 【python】2048
- BZOJ2674 : Attack
- layoutSubviews,setNeedsDisplay
- validator
- 从零开始学ios开发(四):IOS控件(1),Image View、Text Field、Keyboard
- 2011 Asia Fuzhou Regional Contest
- IPython notebook 使用介绍
- windows phone (23) ScrollViewer元素
- windows 查 mac
- [array] leetcode - 54. Spiral Matrix - Medium
- 使用mongoskin操作MongoDB
- 18、实现strStr()
- Acoustic modelling from the signal domain using CNNs
- AndroidStudio中builde.gradle文件详解
- 给视频加上 遮盖层, 移入隐藏, 移开 显示遮盖 ;;; mouseover ,和 mouseout