遍历文件名列表并将它们附加到 Python

Looping over a list of filenames and appending them together in Python

到目前为止,我有一个以文件名的相同部分开头的文件列表,所以我想通配符并获取目录中以文件名的相同部分开头的所有文件名的列表,然后将所有文件附加在一起,以便它只是一个大文件。我知道我需要导入 glob。所以这就是我到目前为止所拥有的。

import glob

filename = glob.glob('1511**.mnd')
data_nov15_hereford = pd.DataFrame()
list = []

for i in filename:
  f_nov15_hereford = pd.read_csv(i, skiprows = 33, sep='\s+',chunksize=30)
  list.append(f_nov15_hereford)
  data_nov15_hereford = pd.concat(list)
  data_nov15_hereford = data_nov15_hereford.convert_objects(convert_numeric=True)

是否有更简单或更好的方法来做到这一点并且实际可行。 谢谢!

import glob

filename = glob.glob('1511**.mnd')
data_nov15_hereford = pd.DataFrame()
frames = []

for i in filename:
    f_nov15_hereford = pd.read_csv(i, skiprows = 33, sep='\s+')
    frames.append(f_nov15_hereford)
data_nov15_hereford = pd.concat(frames)
data_nov15_hereford = data_nov15_hereford.convert_objects(convert_numeric=True)
# save to csv
data_nov15_hereford.to_csv(filename)

  • 不要在 for-loop 中调用 pd.concat()。这样做很大程度上是浪费精力,因为

    data_nov15_hereford = pd.concat(list) 
    

    在循环的每次迭代中为 data_nov15_hereford 分配一个新值。

  • 避免命名变量 list,因为 list 是内置的 Python class。将特定列表分配给 list 可能会导致以后在看似无害的代码中出现令人惊讶的、难以发现的错误,例如 x = list(...)(这会引发 TypeError: 'list' object not callable 错误。)