用Python迭代目录 [英] Iterating through directories with Python

查看:117
本文介绍了用Python迭代目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历给定目录的子目录并搜索文件。如果我收到一个文件,我必须打开它并更改内容并用自己的行替换。

I need to iterate through the subdirectories of a given directory and search for files. If I get a file I have to open it and change the content and replace it with my own lines.

我尝试过:

import os

rootdir ='C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        f=open(file,'r')
        lines=f.readlines()
        f.close()
        f=open(file,'w')
        for line in lines:
            newline = "No you are not"
            f.write(newline)
        f.close()

但我收到错误。我究竟做错了什么?

but I am getting an error. What am I doing wrong?

推荐答案

实际浏览目录的工作方式与编码一样。如果用简单的 print 语句替换内部循环的内容,您可以看到每个文件都被找到:

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

如果您在运行上述操作时仍然收到错误,请提供错误消息。

If you still get errors when running the above, please provide the error message.

这篇关于用Python迭代目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆