Python在开头和结尾加入字符

标签 python python-2.7

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

关于Python在开头和结尾加入字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28314014/

相关文章:

python - str在Python中是如何实现的?

django - 有什么办法可以在django测试客户端中发布字典列表?

Python 正则表达式在文件行首搜索字符串

python - 通过DDP上传文件到Meteor

python - 在 django 模板中使用 python 字符串格式

python - 不能将序列乘以 float 类型的非 int 吗?

python-2.7 - 如何使用广播从具有列表 2d 索引的 2D numpy 数组中获取元素?

python - 在 Dash 中的回调中清除组件

python - Bazel 构建 Retrainer 失败

python-2.7 - 如何提取此列表名称