无法写入文件

时间:2018-08-14 16:21:36

标签: python python-3.x

我有以下代码:

import csv
import operator
import sys

with open('countryInfo.csv','r', encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile, delimiter='\t')
    result = sorted(reader, key = lambda d: float(d['population']),reverse = True)
 #   for row in result:
 #       print(row)
 #   for row in result:
 #      print(row['name'], row['capital'], row['population'])
writer = csv.DictWriter(open('country_simple_info.csv', 'w', encoding='utf-8'), reader.fieldnames)
#with open("country_simple_info.csv", "w", encoding='utf-8') as csvoutfile:
writer.writeheader()
writer.writerows(result)

此代码的目标是编写一个程序,打开一个countryInfo.csv文件,并从每一行中提取国家namecapital城市和population,然后编写一个名为country_simple_info.csv的新文件,在每行中分别包含countrycapitalpopulation,并按population大小对行进行排序,最大的排在前。该文件具有包含其他信息的列,例如continentlanguages等,但是代码应忽略这些信息。在上面的代码中,当我取消注释print语句时,代码可以输出预期的输出-格式如下:

country,capital,population 
China,Beijing,1330044000
India,New Delhi,1173108018
United States,Washington,310232863
.......

但是,我无法写入文件。有任何想法吗?而且,我不允许使用pandas

1 个答案:

答案 0 :(得分:-1)

with open('country_simple_info.csv', 'w', encoding='utf-8') as outputFile:
    writer = csv.DictWriter(outputFile, reader.fieldnames)
    writer.writeheader()
    writer.writerows(result)

使用“ with open”语句将在超出范围时强制outputFile关闭,从而保存写入其中的文本。

希望这会有所帮助。