我希望Python导入一个文件夹中的几个CSV文件并将其连接起来。在Mac和Windows上工作时,我需要一个适用于两者的解决方案。另外,我需要Python以特定方式读取CSV:以;
分隔这是我目前的情况,我必须手动在代码中添加文件:
import pandas as pd
loading_files = Path("Loading Files/")
loading_feb01 = pd.read_csv(loading_files / "Loading FEB 01.csv.csv", sep = ';', header = 0)
loading_feb02 = pd.read_csv(loading_files / "Loading FEB 02.csv.csv", sep = ';', header = 0)
loading_feb03 = pd.read_csv(loading_files / "Loading FEB 03.csv.csv", sep = ';', header = 0)
loading_feb04 = pd.read_csv(loading_files / "Loading FEB 04.csv.csv", sep = ';', header = 0)
loading_feb_raw = [loading_feb01, loading_feb02, loading_feb03,
loading_feb04]
loading_feb = pd.concat(loading_feb_raw)
我希望有一种简单的方法,可以导入所有以“加载”开头的文件,并以分号正确读取,然后进行级联。最重要的是,同样的代码是否也适用于Excel文件(我也想添加一些其他代码)?
我找到了这段代码,能够导入很多文件,但无法获取sep =';'工作:
df = pd.concat([pd.read_csv(f) for f in glob.glob('loading*.csv')], ignore_index = True)
知道我在做什么错吗?
答案 0 :(得分:1)
我刚刚通过结合其他一些答案来解决了这个问题
loading = pd.concat([pd.read_csv(f, delimiter=";") for f in loading_files.glob('Loading*.csv')], ignore_index = True)
答案 1 :(得分:0)
os.listdir()
将返回目录中所有文件的列表。只需遍历名称,检查名称.endswith('.csv')
并动态打开即可
答案 2 :(得分:0)
directory = "Loading Files/"
loading_feb_raw = []
# Iterate over files in directory
for file in os.listdir(directory):
# Only consider files of form "Loading*.csv"
if file.startswith("Loading") and file.endswith(".csv"):
csv = pd.read_csv(file, sep=';', header=0)
# Add read csv to container
loading_feb_raw.append(csv)
# Concatenate contents of container
loading_feb = pd.concat(loading_feb_raw)