Python 重命名文件不适用于>;1 GB文件

Python 重命名文件不适用于>;1 GB文件,python,python-3.x,Python,Python 3.x,我正在使用下面的代码重命名数百个文件,当文件大小小于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

我正在使用下面的代码重命名数百个文件,当文件大小小于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
。它读取内存中的所有文件,并在内存不足时安静地失败


只需
打开每个文件,在一个简单的循环中读取14行,或借助
itertools.islice
以下是工作代码:

    file_path = os.path.join(path, filename) 
    fb=open(file_path)
    secondline=next(islice(fb,1,2))
    fb.close()
    print(secondline)
    new_file_name = secondline[28:28 + 70].rstrip() 
    Filenamenew = new_file_name
    os.rename(file_path, os.path.join(path, Filenamenew))

是否保证您的文件至少有14行?文档中说,即使找不到该行,getline也不会引发异常。另外,您的fourteenline变量的一个例子也不错。是的,每个文件都有一个25行的头,即使它没有数据。