我在同一个目录中有许多具有随机名称的文本文件。我想创建与 txt 文件相同数量的数据帧。此 dfs 必须与 txt 文件同名。
import os
import numpy as np
import pandas as pd
ruta="/path/to/dir/"
files = [f for f in os.listdir(ruta) if f.endswith(".txt")]
#______________________________________________________________________________
#Apertura de los archivos de textos disponibles
tope=len(files)+1
for i in range(1,tope):
exec("e{}=open(ruta+files[i-1],mode='r', encoding='latin 1')".format(i))
这是我正在尝试的,但不完整。你还有什么建议吗?
谢谢。
答案 0 :(得分:1)
数据帧或任何内存文件不一定有名称,但可以分配给某个名称或映射,可能带有 dict
import os
collection = {} # create an empty dictionary
for dirname in os.listdir(): # iterate through all the files
with open(dirname, encoding="latin 1") as fh:
collection[dirname] = fh.read()
如果文件表示应该是数据框的数据,您可以尝试将它们作为数据框读取(例如使用 pandas read_csv
method .. 根据需要调整分隔符)
import pandas as pd
collection = {}
for dirname in os.listdir():
collection[dirname] = pd.read_csv('output_list.txt', sep=" ", encoding="latin 1")
一旦收集到字典中,您可以稍后在程序中按索引引用它们,或者使用 .items()
方法迭代它们
collection["namewhatever.txt"] # refer to a specific object
for name, df in collection.items():
# name and df rotate through each in the collection in this scope
答案 1 :(得分:1)
您绝对不希望创建任意数量的 DataFrame。我同意@ti7 的观点,您至少应该在字典中收集数据帧。
但是如果文件包含兼容的表格数据并且您想一起处理所有数据,您应该将数据编译成一个单独的 DataFrame,并带有一个额外的字段来标识原始文件:
files = [f for f in os.listdir(ruta) if f.endswith(".txt")]
df = pd.DataFrame()
for f in files:
df.append(pd.read_csv(f).assign(file_name=f))