如何遍历文件夹中的所有.txt文件?

时间:2019-04-18 01:16:28

标签: python pandas

我有代码从文件夹中仅读取一个txt文件,但是实际上,我需要遍历所有这些文件。并对每个文件运行相同的步骤并输出结果。由于我有6800个文件,这意味着我无法将所有文件合并到一个数据帧中。

data = 
 pd.read_table("C:path/000007.txt",header=None,delim_whitespace=True)
print(data)


data=data.sort_values(by=4).reset_index(drop = True)

data = data.loc[:,[4,5,6,7]]   #data before process
print(data)

data['hcd'] = data[6] * 0.5 - data[4] * 0.5 + data[4]

data_1 = data[['hcd','vcd','x','y']]  #midpoint and x,y for two points
#print (data_1)

data['hcd2'] = data['hcd']**2
data['vcd2'] = data['vcd']**2

data['x2'] = data['x']**2
data['y2'] = data['y']**2

以此类推.....

我的结果是:

 dis    para result
0  248.87   67.70      1
1  218.96  101.64      1
1    2
Name: result, dtype: int64

但这只是一个txt结果,我想拥有所有文件的结果并保存在一个这样的新txt文件中(还要删除名称:result,dtype:int64):

                                         #1(numbers of 1) #0(numbers of 0)
filename1(for example: 000001.txt):      2                 5
filename1(for example: 000001.txt):      6                 7
 ...... and so on

2 个答案:

答案 0 :(得分:0)

也许尝试使用glob列出匹配的文件:

<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /admin/ was not found on this server.</p>
</body>
</html>

答案 1 :(得分:0)

我建议看看使用os.walk来获取所有文件和目录。它也很方便,因为它也可以遍历子文件夹:

https://www.tutorialspoint.com/python/os_walk.htm

相关问题