Skip to main content
 首页 » 编程设计

Python在开头和结尾加入字符

2025年05月04日12artech

这段代码是用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(文件)

但是我怎样才能得到文件名末尾的"呢?

请您参考如下方法:

  1. 您可以使用'single' 和"double-quotes" 编写字符串文字;你不必从一个里面逃脱另一个。
  2. 您可以在加入 之前使用format 功能应用引号。
  3. 您应该在打开文件时使用 with 语句,这样您就不必显式地关闭它了。

因此:

import os 
with open("files.txt", "w") as f: 
    f.write(' '.join('"{}"'.format(file) for file in os.listdir('.'))