这段代码是用python写的
import os
files = os.listdir(".")
x = ""
for file in files:
x = ("\"" + file + "\" ")
f = open("files.txt", "w")
f.write(x)
f.close()
这行得通,我得到一个包含目录中所有文件的字符串 "foo.txt""bar.txt""baz.txt"
但我不喜欢 for 循环。我不能像那些 Python 专家那样更简洁地编写代码吗?
我试过了
"\"".join(文件)
但是我怎样才能得到文件名末尾的"
呢?
最佳答案
- 您可以使用
'single'
和"double-quotes"
编写字符串文字;你不必从一个里面逃脱另一个。 - 您可以在
加入
之前使用format
功能应用引号。 - 您应该在打开文件时使用
with
语句,这样您就不必显式地关闭
它了。
因此:
import os
with open("files.txt", "w") as f:
f.write(' '.join('"{}"'.format(file) for file in os.listdir('.'))
关于Python在开头和结尾加入字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28314014/