繁体   English   中英

如何将目录中的所有文件拼接成一个文件

[英]How to concatenate all files in the directory into one file

我正在关注一个在线教程(从 2 年前开始,出于某种原因,我上次问问题很重要,因为显然最新版本的 Python 的语法已经更改)。 无论如何,这是我正在使用的代码:

files = [file for file in os.listdir ('./Sales_Data')]
all_months_data=pd.DataFrame()
for file in files:
    df= pd.read_csv("./Sales_Data"+file)
    all_months_data= pd.concat ([all_months_data, df])
all_months_data.to_csv("all_data.csv",index= False)

这是我得到的错误:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13984/1832777700.py in <module>
      2 all_months_data=pd.DataFrame()
      3 for file in files:
----> 4     df= pd.read_csv("./Sales_Data"+file)
      5     all_months_data= pd.concat ([all_months_data, df])
      6 all_months_data.to_csv("all_data.csv",index= False)

~\anaconda3\lib\site-packages\pandas\util\_decorators.py in wrapper(*args, **kwargs)
    309                     stacklevel=stacklevel,
    310                 )
--> 311             return func(*args, **kwargs)
    312 
    313         return wrapper

~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, error_bad_lines, warn_bad_lines, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options)
    584     kwds.update(kwds_defaults)
    585 
--> 586     return _read(filepath_or_buffer, kwds)
    587 
    588 

~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py in _read(filepath_or_buffer, kwds)
    480 
    481     # Create the parser.
--> 482     parser = TextFileReader(filepath_or_buffer, **kwds)
    483 
    484     if chunksize or iterator:

~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py in __init__(self, f, engine, **kwds)
    809             self.options["has_index_names"] = kwds["has_index_names"]
    810 
--> 811         self._engine = self._make_engine(self.engine)
    812 
    813     def close(self):

~\anaconda3\lib\site-packages\pandas\io\parsers\readers.py in _make_engine(self, engine)
   1038             )
   1039         # error: Too many arguments for "ParserBase"
-> 1040         return mapping[engine](self.f, **self.options)  # type: ignore[call-arg]
   1041 
   1042     def _failover_to_python(self):

~\anaconda3\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py in __init__(self, src, **kwds)
     49 
     50         # open handles
---> 51         self._open_handles(src, kwds)
     52         assert self.handles is not None
     53 

~\anaconda3\lib\site-packages\pandas\io\parsers\base_parser.py in _open_handles(self, src, kwds)
    220         Let the readers open IOHandles after they are done with their potential raises.
    221         """
--> 222         self.handles = get_handle(
    223             src,
    224             "r",

~\anaconda3\lib\site-packages\pandas\io\common.py in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)
    700         if ioargs.encoding and "b" not in ioargs.mode:
    701             # Encoding
--> 702             handle = open(
    703                 handle,
    704                 ioargs.mode,

FileNotFoundError: [Errno 2] No such file or directory: './Sales_DataSales_April_2019.csv'

1

​

2

​

我尝试检查/更改拼写/语法错误,它有助于解决其中一个错误。

我还尝试添加最后一行代码,我认为它只会添加更多错误。

如果您继续阅读堆栈跟踪,答案是显而易见的:

FileNotFoundError: [Errno 2] No such file or directory: './Sales_DataSales_April_2019.csv'

for循环中构建文件路径时缺少正斜杠 ( / )。

所以,要修复它:

    files = [file for file in os.listdir ('./Sales_Data')]
    all_months_data=pd.DataFrame()
    for file in files:
        df= pd.read_csv("./Sales_Data/" + file) # This line!
        all_months_data= pd.concat ([all_months_data, df])
    all_months_data.to_csv("all_data.csv",index= False)

更简洁的解决方案是使用方法os.path.join ,请参阅其他 StackOverflow 答案: Create file path from variables

如果我们使用os.path.join

    files = [file for file in os.listdir ('./Sales_Data')]
    all_months_data=pd.DataFrame()
    for file in files:
        df= pd.read_csv(os.path.join("./Sales_Data", file)) # This line!
        all_months_data= pd.concat ([all_months_data, df])
    all_months_data.to_csv("all_data.csv",index= False)

我的最后一个提示是:在提问之前一定要阅读并理解错误信息!

嗨希望你做得很好!

您可以使用pathlib而不是os ,它也是 stdlib 的一部分,因此无需安装任何东西。 在这种情况下,您的代码将如下所示:

import pathlib

import pandas as pd

dirpath = pathlib.Path("sales_data")
# sales_data
# ├── sales_2019_01.csv
# └── sales_2019_02.csv

files = list(dirpath.glob("**/*.csv"))
# [PosixPath('sales_data/sales_2019_01.csv'), PosixPath('sales_data/sales_2019_02.csv')]

all_months_data = []

for file in files:
    df = pd.read_csv(file)
    all_months_data.append(df)

all_months_data_df = pd.concat(all_months_data).reset_index(drop=True)
all_months_data_df.to_csv("all_data.csv", index=False)

但如果您仍然对您的代码有什么问题感兴趣:您丢失了/何时正在阅读 csv: df= pd.read_csv(f"./Sales_Data/{file}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM