我将突出显示您代码中的问题;这应该可以帮助你。目前尚不清楚您真正想要做什么。
import os,sys
path="O:\\103" # this should be r'O:\103'
dir=os.listdir(path)
for file in dir: # do not use file as a variable name as its a built-in
dir=os.path.join(path,file) # here you are overwriting the `dir` variable
print dir
os.system("dir /b "+dir+" > "+file+".txt")
with open('file','r') as f: # 'file' is a string, file is a variable
#f.readline()
text=f.read()
print text
f.close() # you don't need to close the file if you use a with statement.
with open('f','w') as yyy: # here you are trying to open the string 'f'
for xxx in yyy:
# this should be if not xxx.startswith('$'):
if all(not xxx.startswith(x) for x in ('$')):
p=xxx.split("_")[0]
print p
f.writelines(str(p)+"\n") # what is f here? This should be
# .write()
# writelines() takes a sequence
yyy.close() # again, no need to close
如果你有一个目录/home/vivek/test
并且在它里面你有这个:
.
└── vivek
├── v1
│ ├── A.txt
│ ├── B.txt
│ └── C.txt
└── v2
├── D.txt
├── E.txt
└── F.txt
您的目标是打印文件名(或打开文件名并打印其内容):
import os
root_path = '/home/vivek/test'
files = []
for parent,directory,file_list in os.walk(root_path):
if file_list:
for filename in file_list:
files.append(os.path.join(parent,filename))
这将为您提供文件的完整路径列表,如下所示:
['/home/vivek/test/vivek/v2/E.txt',
'/home/vivek/test/vivek/v2/D.txt',
'/home/vivek/test/vivek/v2/F.txt',
'/home/vivek/test/vivek/v1/C.txt',
'/home/vivek/test/vivek/v1/B.txt',
'/home/vivek/test/vivek/v1/A.txt']
现在,你可以做任何你喜欢的事情:
for filename in files:
with open(filename) as f:
print f.readlines()