python两种不同的文件流读写

python两种不同的文件流读写

1、使用try进行异常发现,使用while检测文件末尾进行读取

file_to_read=raw_input("Enterfilenameoftests(emptystringtoendprogram):")
try:
infile=open(file_to_read,'r')
whilefile_to_read!="":
file_to_write=raw_input("Enteroutputfilename(.csvwillbeappendedtoit):")
file_to_write=file_to_write+".csv"
outfile=open(file_to_write,"w")
readings=(infile.readline())
printreadings
whilereadings!=0:
globalcount
readings=int(readings)
minimum=(infile.readline())
maximum=(infile.readline())

2、使用for遍历读取的每一行,进行一次性的读取和输入

result=list()
withopen('../test/parameter.txt')asf:
forlineinf.readlines():
temp=list()
#逐个遍历对应每一行元素,将之转为对应的数据
b=line.strip(",][").split(',')
if(len(b)>=5):
b.pop()
forainb:
a=a.replace('[','').replace(']','')
temp.append(float(a))
result.append(temp)
#print("中途打印的temp是",temp)
#print("加入到result中的结果是",result)

以上就是python两种不同的文件流读写,希望对大家有所帮助。更多python学习指路:python基础教程