我正在使用下面的代码重命名数百个文件,当文件小于 1GB 时效果很好,但是当它遇到较大的文件时,它不会提取任何内容并且生成的文件名是空白的。
import os, linecache
for filename in os.listdir(path):
if not filename.startswith("out"): continue # less deep
file_path = os.path.join(path, filename) # folderpath + filename
fourteenline = linecache.getline(file_path, 14) # maybe 13 for 0-based index?
new_file_name = fourteenline[40:40+50].rstrip() # staring at 40 with length of 50
os.rename(file_path, os.path.join(path, new_file_name))
最佳答案
不要使用 linecache
。它读取内存中的整个文件,并在内存不足时安静地失败。
只需 open
每个文件并在一个简单的循环中读取 14 行,或者在 itertools.islice
的帮助下。
关于python - 重命名文件不适用于 >1 GB 的文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52476567/