Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用请求的名称将数组写入txt文件_Python_Arrays_File Io - Fatal编程技术网

Python 使用请求的名称将数组写入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

我对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()

反转数组后,我需要向用户请求输出文件的名称,然后根据用户输入的内容保存文件。任何帮助都将不胜感激!谢谢

您可以在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
列表。请参阅我的编辑。