我需要遍历给定目录的子目录并搜索文件.如果我得到一个文件,我必须打开它并更改内容并用我自己的行替换它.
我试过这个:
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()
Run Code Online (Sandbox Code Playgroud)
但是我收到了一个错误.我究竟做错了什么?
我是python的新手.我有一个目录,其中包含许多子文件夹和文件.因此,在这些文件中,我必须将一些指定的字符串集替换为新字符串.在java中我使用了这个HashMap
.我将旧字符串存储为键,将新字符串存储为相应的值.我搜索了hashMap中的密钥,如果有一个匹配,我用相应的值替换.是否有类似于Python中的hashMap的东西,或者你可以建议如何解决这个问题.
举一个例子,让我们看一下字符串集是Request,Response.我想将它们更改为MyRequest和MyResponse.我的hashMap是
Key -- value
Request -- MyRequest
Response -- MyResponse
Run Code Online (Sandbox Code Playgroud)
我需要一个与此相当的东西.
我有一个文件夹,里面有不同的子文件夹。我必须遍历所有文件并检查 John 和 Jose 的出现并分别替换为 Mikel 和 Mourinho。
这是我用 Python 编写的脚本。它工作正常但是当我遇到一个.gif
文件时它给了我一个错误并且它没有进一步迭代。
你能告诉我为什么吗?
错误是
Traceback (most recent call last):
File "C:\Users\sid\Desktop\script.py", line 33, in <module>
os.chmod(path ,stat.S_IWRITE)
FileNotFoundError: [WinError 2] The system cannot find the file specified:'C:\Users\sid\Desktop\test\\images/ds_dataobject.gif.bak'
Run Code Online (Sandbox Code Playgroud)
我的代码:
import os,stat
import fileinput
import sys
rootdir ='C:\Users\spemmara\Desktop\test'
searchTerms={"John":"Mikel", "Jose":"Mourinho"}
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
for subdir, dirs, files in os.walk(rootdir):
for file in files:
path=subdir+'/'+file
print(path)
os.chmod(path ,stat.S_IWRITE)
for key,value …
Run Code Online (Sandbox Code Playgroud)