Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.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将列表写入文件_Python_Arrays_List_File - Fatal编程技术网

python将列表写入文件

python将列表写入文件,python,arrays,list,file,Python,Arrays,List,File,从post开始,我一直在使用以下代码将列表/数组写入文件: with open ("newhosts.txt",'w') as thefile: for item in hostnameIP: thefile.write("%s\n" % item) 其中hostnameIP是: 在文件中,我得到了输出: ['localhost', '::1'] ['localhost', '::1'] ['localhost', '::1'] 当我需要说的时候 localhost,

从post开始,我一直在使用以下代码将列表/数组写入文件:

with open ("newhosts.txt",'w') as thefile:
    for item in hostnameIP:
      thefile.write("%s\n" % item)
其中
hostnameIP
是:

在文件中,我得到了输出:

['localhost', '::1']
['localhost', '::1']
['localhost', '::1']
当我需要说的时候

localhost, ::1
localhost, ::1
localhost, ::1
最好的方法是什么?

使用:

with open ("newhosts.txt", "w") as thefile:
    for item in hostnameIP:
        thefile.write("%s\n" % ", ".join(item))
这样,项目的每个部分都将使用“,”作为分隔符打印

但是,如果您想使代码更短,还可以使用换行符连接每个项目:

with open ("newhosts.txt", "w") as thefile:
    thefile.write("\n".join(map(", ".join, hostnameIP)))

您当前正在将列表的字符串表示形式打印到文件中。由于您只对列表的项感兴趣,因此可以使用和参数解包来提取它们:

thefile.write("{}, {}\n".format(*item))

我将使用csv模块,只需在列表列表中调用writerows:

import csv
lines = [['localhost', '::1'], ['localhost', '::1'], ['localhost', '::1']]
with open ("newhosts.txt",'w') as f:
    wr = csv.writer(f)
    wr.writerows(lines)
输出:

localhost,::1
localhost,::1
localhost,::1

从我所看到的,你有一个列表,列表是元素。这就是为什么你会得到你得到的结果。尝试下面的代码(参见第三行的小改动),您将得到想要的结果

with open ("newhosts.txt",'w') as thefile:
    for item in hostnameIP:
      thefile.write("%s\n" % ', '.join(item))

两个答案都很好,干杯!您将接受哪一项?:)
with open ("newhosts.txt",'w') as thefile:
    for item in hostnameIP:
      thefile.write("%s\n" % ', '.join(item))