【问题标题】:How to automate file handling in python如何在python中自动处理文件
【发布时间】:2017-07-05 09:06:19
【问题描述】:

这是我的代码

f1 = open("file1.txt").read( ).splitlines( )
f2 = open("file2.txt").read( ).splitlines( )
print list(itertools.product(f1,f2))

我想为目录中的所有文件运行这个。如何使用 python 来做。我无法使用 glob 执行here 给出的建议。

【问题讨论】:

  • 听说过 for 循环吗?
  • 使用 os.listdir() 循环遍历目录中的每个文件
  • 我无法使用 glob 执行此处给出的建议是什么意思 - 你有错误吗?请展示您迄今为止所做的尝试,包括可能出现的错误。
  • 谢谢@Krishan Mehta 我知道 for 循环,但我不知道在这种情况下实现它。我们在这里寻求建议,请不要仅仅因为你知道一些事情而试图嘲笑别人他们不知道。

标签: python automation file-handling


【解决方案1】:
import glob

#For any kind of file in that directory.

for file in list(glob.glob("*")):     
    # do your work

#For specific kind of file in that directory. like all .py or .txt or .csv file.. etc. 

for file in list(glob.glob("*.file extension")):
    # do your work

【讨论】:

    猜你喜欢
    • 2013-08-24
    • 2017-12-09
    • 1970-01-01
    • 2014-05-22
    • 2015-08-19
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多