是否有更好的方式在 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/