[英]Prints to console. Now I want to print to CSV file
I can read a text file with names and print in ascending order to console.我可以读取带有名称的文本文件并按升序打印到控制台。 I simply want to write the sorted names to a column in a CSV file.
我只想将排序后的名称写入 CSV 文件中的一列。 Can't I take the printed(file) and send to CSV?
我不能把打印的(文件)发送到 CSV 吗? Thanks!
谢谢!
import csv
with open('/users/h/documents/pyprojects/boy-names.txt','r') as file:
for file in sorted(file):
print(file, end='')
#the following isn't working.
with open('/users/h/documents/pyprojects/boy-names.csv', 'w', newline='') as csvFile:
names = ['Column1']
writer = csv.writer(names)
print(file)
You can do something like this:你可以这样做:
import csv
with open('boy-names.txt', 'rt') as file, open('boy-names.csv', 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file, quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow(['Column1'])
for boy_name in sorted(file.readlines()):
boy_name = boy_name.rstrip('\n')
print(boy_name)
csv_writer.writerow([boy_name])
I believe this is adequately covered in the documentation.我相信这在文档中得到了充分的涵盖。
The only tricky part is converting the lines from the file to a list of 1-element lists.唯一棘手的部分是将文件中的行转换为 1 元素列表的列表。
import csv
with open('/users/h/documents/pyprojects/boy-names.txt','r') as file:
names = [[k.strip()] for k in sorted(file.readlines())]
with open('/users/h/documents/pyprojects/boy-names.csv', 'w', newline='') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(['Column1'])
writer.writerows(names)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.