我有几百个大文件(基于行号)。我正在尝试使用循环编写代码。首先,循环读取文件夹中的大文件,其次,它将创建一个与正在读取的文件名相同的文件夹,最后,它将在创建的相同文件夹中对该文件进行切片。这个循环应该遍历文件夹中存在的所有大文件。我的代码如下:
import glob
import os
os.chdir("/test code/")
lines_per_file = 106
sf = None
for file in glob.glob("*.TAB"):
with open(file) as bigfile:
for lineno, line in enumerate(bigfile):
if lineno % lines_per_file == 0:
if sf:
sf.close()
sf_filename = '/test code/201511_sst/sf_{}.txt'.format(lineno + lines_per_file)
sf = open(sf_filename, "w")
sf.write(line)
if sf:
sf.close()我得到的输出如下所示:
In [35]: runfile('/test code/file_loop_16Jan.py', wdir='/test code')
In [36]:我需要一些循环文件的指导,这样我才能实现它。我认为没有错误意味着我遗漏了什么!!请任何人都可以帮助我!
发布于 2017-01-16 17:25:55
sf在开始时被设置为None,因此您永远不会进入if sf循环:不会在任何地方写入任何输出文件。
此外,当你关闭文件时,你必须再次将sf设置为None,否则当你再次关闭时,你会得到“对关闭的文件的操作”。
您希望拆分文件,因此请执行以下操作:
if lineno % lines_per_file == 0:
# new file, close previous file if any
if sf:
sf.close()
# open new file
sf_filename = '/test code/201511_sst/sf_{}.txt'.format(lineno + lines_per_file)
sf = open(sf_filename, "w")
# write the line in the current handler
sf.write(line)因为sf是None,所以它不会调用close (最好是)
在下一次迭代中,当模数匹配时,关闭前一个文件,并使用新文件名创建一个新的句柄。
if sf:
sf.close()旁白:另一个问题是,如果有超过1个大的*.TAB文件,拆分的文件将被覆盖。为了避免这种情况,我会在输出文件中添加输入文件基名,例如(lineno在每个循环中都会重置):
sf_filename = '/test code/201511_sst/{}_sf_{}.txt'.format(os.path.splitext(os.path.basename(file))[0]),lineno + lines_per_file)由你决定
发布于 2017-01-16 18:21:42
因为您已经在使用with语句读取文件,所以您也可以使用相同的语句来写入文件,这样就不需要显式地关闭file对象。请参阅这些链接。
https://docs.python.org/2/reference/compound_stmts.html#with https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
您可以简单地执行以下操作:
with open(file,"w") as sf:
// read/write file content and do your stuff herehttps://stackoverflow.com/questions/41672844
复制相似问题