在写入模式下迭代文件

时间:2012-10-03 04:12:54

标签: python

FOLDER1
  FOLDER2
     FOLDER3
     $$FOLDER4

我只需要FOLDER3,因为我的输出打印为FOLDER3.txt。这是我的代码,我想在写模式下迭代文件夹。

import os,sys
path="O:\\103"
dir=os.listdir(path)
for file in dir:
dir=os.path.join(path,file)
print dir
os.system("dir /b "+dir+" > "+file+".txt")
with open('file','r') as f:
#f.readline()
   text=f.read()
   print text
   f.close()
   with open('f','w') as yyy:
   for xxx in yyy:
   if all(not xxx.startswith(x) for x in ('$')):
    p=xxx.split("_")[0]
    print p
    f.writelines(str(p)+"\n")
yyy.close()

1 个答案:

答案 0 :(得分:1)

我将突出显示代码中的问题;这应该会帮助你。目前尚不清楚你真正想做什么。

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()