【发布时间】:2021-12-02 00:06:38
【问题描述】:
我在包含一些路径的目录中有很多文件。需要浏览所有文件,并将“路径”的第一部分替换为我之前获得的其他文件。请记住,“sw”将始终是拆分后这两个部分之间的边界。
所以里面的文件路径是:
E:\p\folder\folder2\sw\first_step\step1\step2\final
E:\p\folder\folder2\sw\second_step\step1\step2\final
E:\p\folder\folder2\sw\second_step\step56\step333\final
E:\p\folder\folder2\sw\second_step\step1\step2\final
etc
我的代码:
def findReplace(directory, find, replace, filePattern):
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with open(filepath) as f:
s = f.read()
s = s.replace(find, replace)
with open(filepath, "w") as f:
f.write(s)
base_dir = 'F:/Users/User1/Folder/'
path_to_files = '/folder1/folder2/files/'
directory = os.listdir(os.path.join(base_dir, path_to_includes_appl))
for file in directory:
if file == None: continue
with open (file, 'r') as f:
content = f.read().split('\n')
for line in content:
if not line: continue
# Idea here is to sepeare part we need to replace with part that has to stay
old_path, path_to_file = line.split('sw\\')
findReplace(str(directory), old_path, base_dir, ".c")
最终输出应该是:
F:\Users\User1\Folder\sw\first_step\step1\step2\final
F:\Users\User1\Folder\second_step\step1\step2\final
F:\Users\User1\Folder\second_step\step56\step333\final
F:\Users\User1\Folder\second_step\step1\step2\final
注意: 请忽略“/”和“\”之间的差异
任何人都知道我做错了什么,或者对如何实现这一点有更好的想法? 谢谢!
编辑:
这是我的新代码:
base_dir = 'F:/Users/User1/Folder/'
path_to_includes_appl = '/folder1/folder2/files/'
# directory = os.listdir(os.path.join(base_dir, path_to_includes_appl))
directory_path = (os.path.join(base_dir, path_to_includes_appl))
directory = os.listdir(directory_path)
for file in directory:
with open (directory_path+file, 'r') as f:
content = f.readlines()
for line in content:
old_path, path_to_file = line.split('sw\\')
findReplace(directory_path, old_path, base_dir, ".c")
当我运行它时,什么都没有发生,没有错误但也没有更新文件
【问题讨论】:
-
我们不能运行它,所以你必须描述你得到了什么。如果您收到错误消息,那么您应该显示有问题的完整错误(不在评论中)。我们无法读懂你的想法。
-
也许首先使用
print()来查看变量中的内容。它被称为"print debuging",它可以告诉你问题出在哪里。 -
最好读取所有文件,关闭它,更改文本路径并打开文件进行写入并将所有文本保存在文件中。
-
你有错误的缩进 - 你应该在
for-loop 内运行findReplace()(直接在你拆分代码之后)但是你在for-loop 之后运行它 - 所以你只运行它最后价值。 -
在
directory中,您有文件夹中所有文件的列表,但后来您将其转换为字符串-str(directory)并尝试在findReplace中使用它,这是另一个大错误-看起来就像您期望此变量中的单个路径一样。似乎您对变量使用了误导性名称directory。如果您使用print()来查看变量中的内容,那么您会看到这个问题。
标签: python python-3.x parsing path strsplit