python - 使用 open() 内部循环理解 - 获取目录中所有文件的文本内容列表

标签 python pandas

是否有更好的方式在 for 循环中使用 with open(file) as f: f.read() 机制 - 即对多个文件进行操作的循环理解?

我试图将其放入数据框中,以便存在从文件到文件内容的映射。

这是我所拥有的 - 但它似乎效率低下并且不符合Python风格/可读:

documents = pd.DataFrame(glob.glob('*.txt'), columns = ['files'])
documents['text'] = [np.nan]*len(documents)
for txtfile in documents['files'].tolist():
    if txtfile.startswith('GSE'):
        with open(txtfile) as f:
            documents['text'][documents['files']==txtfile] = f.read()

输出:

    files   text
0   GSE2640_GSM50721.txt    | RNA was extracted from lung tissue using a T...
1   GSE7002_GSM159771.txt   Array Type : Rat230_2 ; Amount to Core : 15 ; ...
2   GSE1560_GSM26799.txt    | C3H denotes C3H / HeJ mice whereas C57 denot...
3   GSE2171_GSM39147.txt    | HIV seropositive , samples used to test HIV ...

最佳答案

您的代码看起来完全可读。 也许您正在寻找这样的东西(仅限Python3):

import pathlib

documents = pd.DataFrame(glob.glob('*.txt'), columns = ['files'])
documents['text'] = documents['files'].map(
    lambda fname: fname.startswith('GSE') and pathlib.Path(fname).read_text())

关于python - 使用 open() 内部循环理解 - 获取目录中所有文件的文本内容列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54225978/

相关文章:

python - 将颜色向量传递给 matplotlib-Basemap

python - 如何为不规则采样的时间序列获得漂亮的刻度标签?

python - 如何在python中转换转换数据框

python - Pandas concat 具有不同的索引

python - 属性错误: 'str' object has no attribute 'isnumeric'

python - Pandas - 将日期舍入到 30 分钟

python - 查找图像 channel PyTorch 的平均值和标准差

python - 用python编写命令并在powershell中执行

python - 你如何使用 django-datatable-view

python - os.path.join 产生额外的正斜杠