# 8.第八次 Python文件操作
# 一、创建txt文件,写入文本如下:
# name,sex
# '攀攀','男'
# 提示:换行写入'\n'
#
fp = open(r'C:\Users\xhong\Desktop\Python\Test.txt','w',encoding='utf-8')
fp.write("name,sex\n")
fp.write('攀攀,男')
fp.close()
# 二、把创建好的txt文件转换为csv文件,如视频中csv格式
# 提示:逐行读取,利用split方法。
import csv
fp1 = open(r'C:\Users\xhong\Desktop\Python\Test.txt','r',encoding='utf-8')
fp2 = open(r'C:\Users\xhong\Desktop\Python\Test1.csv','w',encoding='utf-8',newline='')
# writer = csv.writer(fp2) #method 1
# for r in fp1.readlines():
# writer.writerow(r.strip().split(","))
# print(r.strip().split(","))
writer =csv.writer(fp2) #method 2
contents = fp1.readlines()
for content in contents:
writer.writerow(content.strip().split(","))
print(content.strip().split(","))
fp1.close()
fp2.close()
网友评论