保存循环结果为数组或txt文件

时间:2016-11-08 21:05:44

标签: python arrays loops

所以我有一个.txt文件,其中包含以下国家/地区列表:

Japan
Faroe Islands
Libya
South Ossetia
Tunisia
...

对于我现在想要补充的所有国家:“资本是什么”。所以我所做的只是:

import numpy as np
import pandas as pd

data = pd.read_csv('countries.txt')

countries = np.array(data)

for country in countries:
    x = 'What is the capital of ' + country

然后它会遍历每个国家/地区并在国家/地区名称前添加上述句子。但由于我对Python很陌生,我不知道如何将我的循环保存到数组或.txt文件中(无关紧要)。现在它只是一次返​​回(如果我打印或者什么)一行,并且不会“添加所有内容”可以这么说。

提前致谢!

1 个答案:

答案 0 :(得分:1)

你是否经历过这样的事情?

import numpy as np
import pandas as pd

data = pd.read_csv('countries.txt')

countries = np.array(data)

questions = []
for country in countries:
    questions += 'What is the capital of ' + country + '?'

# Do any operation on questions (which will look like ['What is the capital of Japan?', 'What is the capital of Faroe Islands?', ..., 'What is the capital of <country name here>?']

或者,您可以通过执行以下操作将所有问题写入文本文件:

import numpy as np
import pandas as pd

data = pd.read_csv('countries.txt', header=None)

countries = np.array(data)

with open("Questions.txt", "w") as outfile:
    for country in countries[0]:
        question = 'What is the capital of ' + country + '?'

        outfile.write(question) # or use print(question, file=outfile)