简体   繁体   English

遍历目录中的所有文件并查找和替换文本-Python

[英]Iterate through all files in a directory and find and replace text - Python

Baby brand new. 宝贝全新。 This was Frankenstein'ed together from a few similar topics, none of which seemed to cover the necessary step of nesting a find and replace inside a file loop. 这是弗兰肯斯坦(Frankenstein)从几个类似的主题中总结出来的,似乎都没有涵盖在文件循环内嵌套查找和替换的必要步骤。

I am attempting to iterate through every file in a folder (not recursively, I only have one folder level) of a specific type (listed here as a '.LIC') and replace a short bit of text. 我试图遍历特定类型(此处列为“ .LIC”)的文件夹中的每个文件(不是递归地,我只有一个文件夹级别),并替换一小段文本。 The following is as close as I could come: 以下是我可能接近的内容:

import glob, os, fileinput
from glob import glob
root_dir = r"myPath"
os.chdir(root_dir)
    for file in glob, glob('*.LIC'):
    filename = str(file)
    with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace('findText', 'replaceText'),  end='')

As you can imagine this went swimmingly. 可以想象,这一切顺利进行。 The error code is placed below. 错误代码位于下面。

OSError                                   Traceback (most recent call last)
<ipython-input-61-e2fd0e9a5df9> in <module>()
      6     filename = str(file)
      7     with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
----> 8         for line in file:
      9             print(line.replace('findText', 'replaceText'), end='')
     10 

C:\Users\Me\Anaconda3\lib\fileinput.py in __next__(self)
    246     def __next__(self):
    247         while True:
--> 248             line = self._readline()
    249             if line:
    250                 self._filelineno += 1

C:\Users\Me\Anaconda3\lib\fileinput.py in _readline(self)
    333                     pass
    334                 # The next few lines may raise OSError
--> 335                 os.rename(self._filename, self._backupfilename)
    336                 self._file = open(self._backupfilename, self._mode)
    337                 try:

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<function glob at 0x00000000013D3400>' -> '<function glob at 0x00000000013D3400>.bak'

I think my problem is nesting a reference to 'file', but I am unsure how to resolve this. 我认为我的问题是嵌套对“文件”的引用,但是我不确定如何解决此问题。

Thank you for the help in advance. 谢谢您的帮助。

You should loop over the result of glob and not a tuple with the function object glob : 您应该遍历glob的结果,而不是使用功能对象glob的元组:

for filename in glob('*.LIC'):
    with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace('findText', 'replaceText'),  end='')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM