如何使用 with 语句动态打开文件进行写入



我正在尝试根据字段逐行将一个大文件拆分为未知数量的文件。在这种情况下,我希望所有日期为 2016 年 7 月的记录写入一个文件,将 2016 年 8 月写入另一个文件,依此类推。我不想对文件进行两次梳理,首先填充需要创建的文件列表,然后实际写入它们。

我的第一个想法是创建一个字典,其中键是文件名(基于日期(,返回是一个将写出到 csv 文件的类。

import csv
class testClass:
a = None
k = None
def __init__(self,theFile):
with open(theFile,'wb') as self.k:
self.a = csv.writer(self.k)

def writeOut(self,inString):
self.a.writerow(inString)
testDict = {'07m19':testClass('07m19_test2')}

testDict['07m19'].writeOut(['test'])

当我尝试运行它时,出现以下错误:

ValueError: I/O operation on closed file

这是有道理的,当类完成初始化时,File已关闭。

我认为 with 语句是必需的,因为文件非常大,我无法将其全部加载到内存中。话虽如此,我不确定如何解决这个问题。

你不一定需要一个类。假设您的输入文件是 csv 文件,并且在第一列中具有月份的全名:

with open('path/to/input') as infile:
for rownum,row in enumerate(csv.reader(infile),1):
month = row[0]
with open('path/to/output_{}.csv'.format(month), 'a') as outfile:
if not rownum%100: print("Processed row", rownum, end='r', flush=True)
csv.writer(outfile).writerow(row)
print("Processed row", rownum)

我无法将其全部加载到内存中

您不会通过open文件将其全部加载到内存中。您只需创建一个文件对象。当您执行f.read()时,将其所有内容作为字符串加载到内存中。

所以你可以做到:

class testClass:
def __init__(self,theFile):
self.k = open(theFile,'wb')
self.a = csv.writer(self.k)
def writeOut(self,inString):
self.a.writerow(inString)
def __del__(self):
self.k.close()

因为不能保证在执行结束时调用__del__,所以你可能希望添加一个close方法,并像调用文件一样调用它。


def __init__(self,theFile):
self.k = open(theFile,'wb')
self.a = csv.writer(self.k)

最新更新