简体   繁体   English

打印到控制台。 现在我想打印到 CSV 文件

[英]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.

相关问题 我想将输入文本从文本框打印到控制台。 下面是我的代码 - I want to print the entry text from textbox to console. Below is my code python打印到文件可以在控制台中正确打印,但不能在文件中打印 - python print to file prints correctly in console but not in file 错误不会打印到 Pycharm 控制台。 仅在日志文件中。 如何让它打印到控制台? - Bugs won't print to Pycharm console. Only in log file. How to make it print to Console? 我只想打印 csv 文件的第二行 - I want to print only second row of my csv file 将数据挖掘到csv文件中,现在我想处理要保留的数据 - Mined Data to a csv file, now I want to process the data I wish to keep 我想在 csv 文件中写入,它只写入最后一个值(我打印该值并且它有效,但在 csv 中没有) - I want to write in csv file and it only write the last value (I print the value and it work but in csv not) 在控制台中打印,但在格式化为CSV时不打印 - Prints in console but not when formatted to CSV Python:读取csv并打印到控制台。 正在打印奇怪的字符 - Python: reading a csv and printing to console. strange characters are being printed 添加了代码,但现在无法正确打印到 CSV 文件 - Added code and now it's not print correctly to CSV file 我想使用 Python 从 csv 文件打印经度和纬度数据 - I want to print longitude and latitude data from a csv file using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM