将字符串转换为文本文件时添加行

时间:2016-03-21 18:02:00

标签: python text-files

的Python

我有1000多个带有数字连续名称的文件,例如IMAG0000.JPG,我已将其保存为列表,转换为字符串,并保存为文本文件。我希望文本文件看起来像这样:

IMAG0000.JPG
IMAG0001.JPG
IMAG0002.JPG
IMAG0003.JPG
...

目前,它看起来像:

IMAG0000.JPGIMAG0001.JPGIMAG0002.JPGIMAG0003.JPG...

我无法弄清楚在哪里放置\ n以使其正确格式化。这就是我到目前为止......

import glob

newfiles=[]
filenames=glob.glob('*.JPG')
newfiles =''.join(filenames)

f=open('file.txt','w')
f.write(newfiles)

2 个答案:

答案 0 :(得分:3)

您使用空字符串''而不是'\n'进行连接。

newfiles = '\n'.join(filenames)
f = open('file.txt','w')
f.write(newfiles) # keep in mind to use f.close()

或更安全(即释放文件句柄):

with open("file.txt", w) as f:
    f.write('\n'.join(filenames))

或者不是连接所有内容:

with open("file.txt", w) as f:
    for filename in filenames:
        f.write(filename + '\n')

答案 1 :(得分:2)

试试这个:

newfiles = '\n'.join(filenames)

旁注:it's good practice to use the with keyword处理文件对象时,所以代码为:

f=open('file.txt','w')
f.write(newfiles)

会变成:

with open('file.txt','w') as f:
    f.write(newfiles)

这样您就不需要明确地f.close()来关闭文件了。