一、前言
Python读写文件的代码有许多形式,虽然十分简单,但是每次使用时都需要查找才能用上。所以鄙人用自己贫乏的Python功力编写了一个读写模块的模板,希望最大化方便有文件读写需求的朋友。
二、Python写文件
- 首先编写一个写文件函数
def writeData(data,path):
with open(path, encoding="utf-8", mode="a") as txt:
txt.writelines(data+'\n')
- 然后是调用writeData函数,实现每调用一次该函数就向文件写入一行
#this is write data template
#generate data for writing
data = []
a = 65
for i in range(0,26):
data.append(chr(a))
a +=1
#The above function is generating data for writing
text = 'readWriteData.txt'
with open(text,'w') as txt:
txt.write('')
# write a line each circle
for i in range(0,len(data)):
writer.writeData(data[i],text)
print(data[i])
结果:A ——Z
三、读文件
- 写文件函数
def read_line(path,index):
with open(path,'r') as txt:
line = txt.readlines()
return line[index][0]
- 然后是调用read_line函数,实现每调用一次该函数就返回文件的一行
#this is write data template
text = 'readWriteData.txt'
for i in range(0,26):
line = reader.read_line(text,i)
print(line)
结果:A——Z
四、模块化
- 函数文件 read_writer_API.py
def writeData(data,path):
with open(path, encoding="utf-8", mode="a") as txt:
txt.writelines(data+'\n')
def read_line(path,index):
with open(path,'r') as txt:
line = txt.readlines()
return line[index][0]
- 实现写文件 write_user.py
#this is write data template
import read_writer_API as writer
data = []
a = 65
for i in range(0,26):
data.append(chr(a))
a +=1
# The above function is generating data for writing
text = 'readWriteData.txt'
with open(text,'w') as txt:
txt.write('')
# write a line each circle
for i in range(0,len(data)):
writer.writeData(data[i],text)
print(data[i])
- 实现读文件 read_user.py
#this is write data template
import read_writer_API as reader
text = 'readWriteData.txt'
for i in range(0,26):
line = reader.read_line(text,i)
print(line)