【发布时间】:2022-07-01 21:25:33
【问题描述】:
我有一个简短的 Python 脚本,它可以打开一个目录并将所有文件名放入一个 .txt 文件中。我尝试了几种方法在每个文件名后添加一个新行,但不能这样做。我也想把整个字符串转成大写。
这是我所拥有的:
import os
#Path where the photos are stored
path1 = r"V:\DATABASES\0 Suspension\Suspensia Pictures"
#Variable to list all the files in the dorectory
file_dir = os.listdir(path1)
#Opens a new text file called Pics
newfile = open('Pics.txt','w')
#Writes lines in the file as a string
newfile.write(str(file_dir))
#Prints out all the file names
#print(file_dir)ode here
我对新行的想法是在newfile.write(str(file_dir)) 行之后添加print('\n')。然而,这并没有奏效。
至于大写我不知道把.upper()放在哪里。
感谢您的帮助
【问题讨论】:
-
print打印到控制台。另一方面,newfile.write('\n')会将该换行符发送到您希望它去的文件中。 -
或扩展 JNevill 所说的内容,只需将现有行更改为
newfile.write(str(file_dir)+"\n") -
对于大写要求,
.upper()是字符串对象的方法。所以newfile.write(str(file_dir).upper())应该可以解决问题。把它们放在一起:newfile.write(str(file_dir).upper() + "\n") -
我试过了,但我仍然得到一个巨大的列表 (
['Thumbs.db', 'X01BJ0004', 'X01BJ0026', 'X01BJ0026.JPG', ....]),我不确定为什么它是一个列表 -
啊。是的。好的。
file_dir是列表对象而不是字符串。忽略了那部分。在这种情况下,您想要“加入”您的列表而不是str(file_dir),这会将您的列表转换为字符分隔的字符串。在这种情况下,分隔符将是换行符:newfile.write(file_dir.join("\n"))
标签: python