Python文件读写保存操作的示例代码-创新互联
记录下第一次使用Python读写文件的过程,虽然很简单,第一次实现其实也有些注意的事项。

单个文件的读操作:
我们先假设一个需求如下:
- 读取一个test.txt文件
- 删除指定字符之前的文本
需求明白之后,下面开始动手写代码,代码很简单。就直接上全部的,细节看注释:
import sys
filePath = "/Users/xxxxxx/Desktop/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)
网页名称:Python文件读写保存操作的示例代码-创新互联
分享网址:http://www.jxjierui.cn/article/dhejii.html


咨询
建站咨询
