文件读操作
假设需求:
- 读取一个
test.txt文件 - 删除指定字符之前的文本
代码:
import sys
filePath = "/Users/aa/test.txt"
# 打开文件
files = open(filePath, 'r')
# 转成list
f_list = files.readlines()
tempIndex = 0
# 对f_list 循环 每个index对应一行数据
for index in range(len(f_list)):
# temp是获取一行的数据
temp = f_list[index]
# 判断"test"是不是temp这行数据的首位 如果是首位 result为true
result = temp.find("test") == 0
if result:
# 如果是首位 这就是我们要删除的位置 获取他的index
tempIndex = index
break
# 存放新数据
tempContainer = []
for index in range(len(f_list)):
if index > tempIndex:
# tempIndex之前的数据我们不处理,把tempindex之后的数据存到新的list里面
tempContainer.append(f_list[index])
# 这就获得了我们需要的新数据
print(tempContainer)注意点:
- 直接用
open获取的数据无法进行处理,先转成可以处理的数据,比如list或者字典等。 - python的
open和C的类似,有r,r+, w, w+等各种状态,见具体介绍
open函数的常见操作方式
1、r 打开只读文件,该文件必须存在。2、r+ 打开可读写的文件,该文件必须存在。
3、w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。 4、w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
多文件读写
假设需求:
- 多个文件都要处理
- 和上面的
test.txt处理方式类似 - 处理完之后保存到一个新文件夹内
实现思路:
- 把文件放在一个文件夹内
- 获取这个文件夹内所有的文件名,拼接成文件路径
- 然后创建一个空的新文件夹,用新的空文件夹加上原始的文件名拼接成新的路径然后写入进去
代码:
import os
# 初始的文件夹路径
filePath = "/Users/aa/fileDocument"
# 存放新文件的空白文件夹
newFilePath = "/Users/aa/newFileDocument"
# 获取文件夹下所有文件名
fileNames = os.listdir(filePath)
for file in fileNames:
# 如果当前的文件名包含了'txt',就当它是正确的文件(并不严谨)
if file.find("txt") >= 0:
# 拼接成我们要读取的完整路径
fileFullPath = filePath + "/" + file
# open 函数 默认是 'r'类型 ,
singleFile = open(fileFullPath)
# 转换成list数据
singleFile_list = singleFile.readlines()
tempIndex = 0
for index in range(len(singleFile_list)):
temp = singleFile_list[index]
result = temp.find("min") == 0
if result:
tempIndex = index
break
# 拼接新的文件路径
newSingleFileFullPath = newFilePath + "/" + file
# 以 w 方式打开新的空白文件
newFile = open(newSingleFileFullPath, 'w')
for index in range(len(singleFile_list)):
if index > tempIndex:
# 写入tempindex行之后的数据
newFile.writelines(singleFile_list[index])
newFile.close()
评论列表(0条)