简体   繁体   English

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

[英]Adding line when converting string to text file

Python 蟒蛇

I have 1000+ files with numerically consecutive names like IMAG0000.JPG that I have saved as list, converted to string, and saved as a text file. 我有1000多个文件,这些文件具有数字连续名称,例如IMAG0000.JPG ,我已将其保存为列表,转换为字符串并另存为文本文件。 I want the text file to look like this: 我希望文本文件看起来像这样:

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

Currently, it looks like: 当前,它看起来像:

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

I can't quite figure out where to put \\n to make it format correctly. 我不太清楚在哪里放置\\ n使其正确格式化。 This is what I have so far... 这是我到目前为止所拥有的...

import glob

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

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

You concat with an empty string '' instead of '\\n' . 您使用空字符串''代替'\\n'

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

or safer (ie releasing the file handle): 或更安全(即释放文件句柄):

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

or instead of concatting everything: 或代替包容一切:

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

Try this: 尝试这个:

newfiles = '\n'.join(filenames)

Side note: it's good practice to use the with keyword when dealing with file objects, so the code: 旁注:在处理文件对象时, 最好使用with关键字 ,因此代码如下:

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

would become: 会成为:

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

That way you do not need to explicitly do f.close() to close the file. 这样,您无需显式执行f.close()即可关闭文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM