//目录

Python语言程序设计基础(7)—— 文件和数据格式化

返回字符串

file = input()

#返回字符串
fo = open(file,"r").read(6)
print(fo)

 

返回列表形式

file = input()
fo = open(file,"r")
#print(fo)
#返回列表形式
print(fo.readlines(-1))
file = input()
fo = open(file,"r")

for line in fo.readlines():
    print(line.replace('\n',""))
fo.close()
file = input()
fo = open(file,"r")
for line in fo:
    print(line.replace('\n',""))
fo.close()

 

w+ 

打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。

fname = input()
fo = open(fname,"w+")
ls = ["TreeDream","love","sea"]

fo.writelines(",".join(ls))
fo.seek(0)
for line in fo:
    print(line)
fo.close()

 

csv

国际通用数据存储格式,使用逗号分隔的表示方式

fo = open("data.csv","r")
'''
ls = []
for line in fo:
    line = line.replace('\n',"")
    ls.append(line.split(","))
print(ls)
fo.close()'''

for line in fo:
    line = line.replace('\n', '')
    ls = line.split(',')
    lns = ""
    for s in ls:
        lns += "{}\t".format(s)
    print(lns)
fo.close()

 

csv读写

fr = open("data.csv","r")
fw = open("out.csv","w")

ls = []
for line in fr:
    line = line.replace("\n","")
    ls.append(line.split(','))
print(ls)

for i in range(len(ls)):
    for j in range(len(ls[i])):
        if ls[i][j].replace('.','').isnumeric():
            ls[i][j] = "{:.2%}".format(float(ls[i][j])/100)
            #print(ls[i][j])

for row in ls:
    print(",".join(row))
    fw.write(",".join(row)+"\n")

 

posted @ 2018-10-21 16:43  小草的大树梦  阅读(615)  评论(0编辑  收藏  举报