python读取txt、csv文件

时间:2022-02-13 19:57:02

txt:

f = open("G:/22.txt","w")
str = "user1=1\npwd1=2\nuser2=3\npwd2=4\nuser3=5\npwd3=6"
f.write(str)
f.flush()
f.close()

dict={}
list1=[]
file = open("G:/22.txt","r")
ss = file.readlines()
print(ss)
for i in ss:
list1 = i.split("=")
print(list1)
dict[list1[0]] = list1[1].splitlines()[0] #每一个后面都会有\n,所以需要去掉
file.close()

print(dict)
for ll in dict:
print(ll+ ":"+dict[ll])

python读取txt、csv文件


csv:

list = ["user1=1","pwd1=2","user2=3","pwd2=4","user3=5","pwd3=6"]
out = open("G:/1.csv","w",newline="")#newline="" 加入后每一行最后不会有空行
csv_writer = csv.writer(out)
csv_writer.writerow(list)
out.close()

out = open("G:/1.csv","r")
data = csv.reader(out)
print(data)
for text in data:
print(text)
out.close()
python读取txt、csv文件