python读写文件

1.读取文件的对象:fin = open("data.txt")

fin = open("input.txt")
for line in fin:
    print(line.strip())
fin.close()

2.写出文件的对象:fout = open("data.txt","w")

fout = open("output.txt","w")
fout.write("max value:"+str(max)+"\n")
fout.write("min value:"+str(min)+"\n")
fout.write("sumv value:"+str(sumv)+"\n")
fout.write("avg value:"+str(sumv/count))

3.读取文件的全内容:whole_data = fin.read()

sql = open("bigsql.sql").read()
print(sql)

4.按行读取文件的内容:for line in fin:print(line)

for line in fin:
    number = int(line.strip())

5.写出一行数据到文件:fout.write("abc\n")

fout.write("max value:"+str(max)+"\n")
fout.write("min value:"+str(min)+"\n")

6.文件的关闭:fin.close()和fout.close()

fin.close()
fout.close()

7.写出大文件时刷新内存到文件:fout.flush()

8.综合练习

fin = open("input.txt")

min = 10000
max = 0
sumv = 0
count = 0
for line in fin:
    number = int(line.strip())
    if numbermax:
        max = number
        sumv += number
        count += 1
print("max value:",max)
print("min value:",min)
print("sumv value:",sumv)
print("avg value:",sumv/count)

fout = open("output.txt","w")
fout.write("max value:"+str(max)+"\n")
fout.write("min value:"+str(min)+"\n")
fout.write("sumv value:"+str(sumv)+"\n")
fout.write("avg value:"+str(sumv/count))

fin.close()
fout.close()

转载于:https://my.oschina.net/u/3055497/blog/3080853

你可能感兴趣的:(python读写文件)