python读取多个文件 [英] read multiple files by python

查看:115
本文介绍了python读取多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须打开几个文件,比如说 50 个名为 1.txt、2.txt、3.txt 等等的文件,并且必须一一读取它们.我可以阅读它们的方式是

data = loadtxt("1.txt", float)

所以文件名被用作字符串,我不能使用任何循环来读取它们.而且单独读取每个文件非常繁琐.有没有办法使用循环来读取所有文件?谢谢.

解决方案

您可以轻松构造一个包含整数的字符串:

<预><代码>>>>'{0}.txt'.format(1)'1.txt'

循环执行:

for i in range(50):data = loadtxt('{0}.txt'.format(i + 1), float)

鲍勃是你的叔叔.

I have to open several files, say 50 files named 1.txt, 2.txt, 3.txt, ... so on and have to read them one by one. The way I can read them is

data = loadtxt("1.txt", float)

So that the file name is used as string and I can't use any loop to read them. And it is very tedious to read each files individually. Is there any way to use a loop to read all files? Thanks.

解决方案

You can easily construct a string with an integer in it:

>>> '{0}.txt'.format(1)
'1.txt'

Do that in a loop:

for i in range(50):
    data = loadtxt('{0}.txt'.format(i + 1), float)

and Bob's your uncle.

这篇关于python读取多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆