按文件块循环,每10个文件执行一次操作
我正在使用谷歌的Colab工具,我的文件在我的云盘里,像这样:
M0000.csv
M0001.csv
M0002.csv
.
.
.
M0099.csv
我需要处理100个文件,每10个文件做一次操作。我想把这10个文件里的所有文本保存到一个列表里,像这样:
all_text[0] = list of text in file from 1 to 10
.
.
all_text[9] = list of text in file from 91 to 100
这是我用来遍历所有文件的代码(但没有实现每10个文件循环一次——我不知道怎么做):
dir = 'drive/My Drive/Tri/'
pd.options.display.max_colwidth = 5000
#Loop for all file
for file in sorted(glob.glob(dir + "*.csv")):
print(f"File: {file}")
# Check the number of columns in the file
df = pd.read_fwf(file, header=None, on_bad_lines='skip', delimiter="\n")
# Loop inside each file
for i in range(len(df)): # Loop over the rows ('i')
#code to do
print("All Text:", all_text)
2 个回答
0
概述
如果我理解你的问题没错的话,你是想把10个文件里的所有文字放到一个列表里。你要处理100个文件,这样你最后会得到10个列表。
文件分组
我的第一步建议是把这些文件分成每组10个,像这样。
import numpy as np
import pandas as pd
# number of files to group
n_file = 10
# file name list which is your glob statement
fn_list = [f'dummy_file_{str(i).zfill(3)}.csv' for i in range(100)]
# put it in a numpy array to quickly group into sets of n
fn_group_of_n = np.array(fn_list).reshape(-1, n_file)
加载和追加行为
接下来,你就有了10个文件的组,可以把它们加载并追加到一个列表里。这需要你重新调整一下追加的方式。
# place to store the text list for each selection of n files
text_by_n = []
# for each set of n files
for file_selection in fn_group_of_n:
list_of_text_in_file_selection = []
for file in file_selection:
# your code
df = pd.read_fwf(file, header=None, on_bad_lines='skip', delimiter="\n")
# this you'll need to replace with something that works for your df format
for row in df.iterrows():
list_of_text_in_file_selection.append(row)
text_by_n.append(list_of_text_in_file_selection)
## optional flattening
# flat = [x for xs in list_of_text_in_file_selection for x in xs]
# text_by_n.append(flat)
限制
没有示例文件,很难具体说明追加的行为,但这会导致你得到一个包含多个子列表的列表。你可能想把这些子列表合并成一个平坦的列表,可以参考这个方法。我无法确认iterrows的行为,因为我不知道你的数据框的结构,但你可能想用row.values而不是直接用row。
0
记录一下你处理了多少个文件。如果这个数字能被十整除,那就做你额外的事情。
filenumber = 0
for file in sorted(glob.glob(dir + "*.csv")):
filenumber += 1
if filenumber % 10 == 0:
# do your extra thing