我对Python很陌生,而且我对使用文件I / O相当陌生。我无法想出如何将数组写入用户输入名称的新txt文件。以下是我写的代码:
def main():
# Opens file
fh = open("A5Nums.txt", "r")
array = [ ]
# Reads numbers into an array
for line in fh.readlines():
for i in line.split():
array.append(int(i))
# Prints the array
print (array)
# Reverses the array
array.reverse()
# Prints the reversed array
print (array)
# Closes the input file
fh.close()
main()
反转数组后,我需要从用户请求输出文件的名称,然后根据输入的内容保存文件。任何帮助,将不胜感激!谢谢!
答案 0 :(得分:1)
您可以在Python 3.x中获取用户的文件名
outfile = input("Please name your output file")
或Python 2.x
outfile = raw_input("Please name your output file")
然后像这样写
with open(outfile, "w+") as fOut:
strArray = list(map(str, array))
fOut.writelines(strArray)