我试图遍历特定类型的文件夹中的每个文件(不是递归地,我只有一个文件夹级别)(此处列为“.LIC”)并替换一小段文本。以下内容尽可能接近:
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='')
你可以想象这是游泳。错误代码放在下面。
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'
我认为我的问题是嵌套对'file'的引用,但我不确定如何解决这个问题。
提前感谢您的帮助。
答案 0 :(得分:2)
你应该遍历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='')