我是一个完整的Python Newb
我需要遍历查找.txt文件的目录,然后单独读取和处理它们.我想设置它,以便脚本所在的任何目录都被视为此操作的根目录.例如,如果脚本位于/ bsepath/workDir中,那么它将循环遍历workDir及其子项中的所有文件.
到目前为止我所拥有的是:
#!/usr/bin/env python
import os
scrptPth = os.path.realpath(__file__)
for file in os.listdir(scrptPth)
with open(file) as f:
head,sub,auth = [f.readline().strip() for i in range(3)]
data=f.read()
#data.encode('utf-8')
pth = os.getcwd()
print head,sub,auth,data,pth
Run Code Online (Sandbox Code Playgroud)
这段代码给我一个无效的语法错误,我怀疑是因为os.listdir不喜欢标准字符串格式的文件路径.另外,我不认为我正在做循环行动.如何在循环操作中引用特定文件?它被打包为变量吗?
任何帮助都是适当的
pok*_*oke 10
import os, fnmatch
def findFiles (path, filter):
for root, dirs, files in os.walk(path):
for file in fnmatch.filter(files, filter):
yield os.path.join(root, file)
Run Code Online (Sandbox Code Playgroud)
像这样使用它,它将在给定路径中的某个地方(递归地)找到所有文本文件:
for textFile in findFiles(r'C:\Users\poke\Documents', '*.txt'):
print(textFile)
Run Code Online (Sandbox Code Playgroud)