import csv
# 一、创建txt文件,写入文本如下:
# name,sex
# '攀攀','男'
# 提示:换行写入'\n'
fp = open(r'D:\work\python\temp\test.txt', 'w')
fp.write('name,sex\n攀攀,男')
fp.close()
# 二、把创建好的txt文件转换为csv文件,如视频中csv格式
# 提示:逐行读取,利用split方法。
fp = open(r'D:\work\python\temp\test.txt', 'r')
contents = fp.read()
fp = open(r'D:\work\python\temp\test.csv', 'w',newline='')
writer = csv.writer(fp)
for content in contents.split('\n'):
# print(content)
writer.writerow((content.split(',')[0], content.split(',')[1]))
fp.close()
fp = open(r'D:\work\python\temp\test.csv', 'r')
readers = csv.reader(fp)
for reader in readers:
print(reader)
网友评论