使用 Python 遍历目录 [英] Iterating through directories with Python

查看:18
本文介绍了使用 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.

针对 Python3 更新

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

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

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