我可以讀取帶有名稱的文本檔案并按升序列印到控制臺。我只想將排序后的名稱寫入 CSV 檔案中的一列。我不能把列印的(檔案)發送到 CSV 嗎?謝謝!
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)
uj5u.com熱心網友回復:
你可以這樣做:
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])
uj5u.com熱心網友回復:
我相信這在檔案中得到了充分的涵蓋。
唯一棘手的部分是將檔案中的行轉換為 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326227.html
