我试图将所有 .txt 文件合并到一个目录中,并在最后一个之后输出它们。
我有以下文件系统结构:
objects
object1
attribute1.txt
attribute2.txt
attribute3.txt
object2
attribute1.txt
attribute2.txt
attribute3.txt
and so on...
我查过这段代码
for subdir, dirs, files in os.walk(rootdir):
for file in files:
# collect the information
我正在寻找一个 for 循环
for subdir, dirs, files in os.walk(rootdir): # <- what do I need to change here?
for object in objects: # <- how to implement this line correctly?
for file in files:
# collect the information
print(information)
但我必须知道如何做到这一点,因为我对 python 非常陌生。
编辑:
Python的连接文本文件并没有回答我的问题,因为没有实际的循环,但只用文件名称的数组。
您显示的第一个循环将遍历所有文件。并且文件的路径存储在subdir
如果你运行:
for subdir, dirs, files in os.walk(rootdir):
block=""
for file in files:
block+=subdir+"/"+file
print block
你会看到你得到了所有的文件。所以现在代替print
语句把你想要读取文件的命令和内容存储到一个变量中(你应该用 path 读取文件subdir+"/"+file
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句