Python 使用请求的名称将数组写入txt文件
我对Python非常陌生,对文件I/O也非常陌生。我很难想到如何将数组写入用户输入名称的新txt文件。以下是我编写的代码:Python 使用请求的名称将数组写入txt文件,python,arrays,file-io,Python,Arrays,File Io,我对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(): a
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()
反转数组后,我需要向用户请求输出文件的名称,然后根据用户输入的内容保存文件。任何帮助都将不胜感激!谢谢 您可以在Python 3.x中从用户处获取文件名
outfile = input("Please name your output file")
或者Python2.x
outfile = raw_input("Please name your output file")
那就这样写吧
with open(outfile, "w+") as fOut:
strArray = list(map(str, array))
fOut.writelines(strArray)
我需要把它放在main中吗?是的,在
fh.close()
之后,你可以把下面几行放进去。你可以使用map
将int
列表转换为str
列表。请参阅我的编辑。