python - 如何在 python 中使用 glob.glob 从具有不同名称的多个输入文本文件中写入多个输出文本文件?
问题描述
我是python的初学者。我想在 python 中从 50 个输入文本文件中写入 50 个输出文件。例如,我有输入文本文件,如:
bottom_0cm_Box_0_B_90_wave_1.txt
bottom_0cm_Box_45_B_135_wave_1.txt
bottom_0cm_Box_90_B_180_wave_1.txt
...
top_0cm_Box_0_B_90_wave_1.txt
top_0cm_Box_45_B_135_wave_1.txt
top_0cm_Box_90_B_180_wave_1.txt
...
在一个文件中,我有 1000 个事件,我必须为每个事件做一些计算,所以我循环了所有 1000 个事件。我有以下代码:
file = glob.glob("/position/*.txt")
print file
print len(file)
for f in file:
with open(f, 'rb') as input:
all_lines = [line for line in input]
x = np.arange(1,1025) #x value is common for all the events
Amplitude=list()
for j in range(1,1000):
y2 = np.array(all_lines[1032*j+8:1032*(j+1)],dtype=float)
x22 = list(x)
y2_=list(y2)
y22 = [((i / 4096)-0.5) for i in y2_]
min_y2 = min(y22) # Find the maximum y2 value
index_min_y2 = y22.index(min_y2) #index for minimum of y2
min_x2 = x[y22.index(min_y2)]
print 'minimum x2', min_x2, 'minimum y2', min_y2
Amplitude.append(round(min_y2, 2))
with open ('bottom_0cm_Box_0_B_90_amplitude.txt', 'w') as fo:
for d in Amplitude:
fo.write(str(d) + '\n')
我想写:
- 输入带有
bottom_0cm_Box_0_B_90_amplitude.txt
输出文件名称的文本文件bottom_0cm_Box_0_B_90_wave_1.txt
。 - 输入文件名和
bottom_0cm_Box_45_B_135_amplitude.txt
输出文件名bottom_0cm_Box_45_B_135_wave_1.txt
等等。
解决方案
您可以将输入文件的名称拆分为基本名称和扩展名,用不同的后缀替换基本名称,将它们连接成一个全名,然后将基本名称与一个新的目录名连接起来作为一个完整的路径名。
添加:
import os.path
然后改变:
with open ('bottom_0cm_Box_0_B_90_amplitude.txt', 'w') as fo:
到:
basename, ext = os.path.splitext(os.path.basename(f))
basename = basename[:-len('wave_1')] + 'amplitude'
with open (os.path.join(new_dir, basename + ext), 'w') as fo:
此外,您不需要将所有结果保存到Amplitude
列表中,因为之后您所做的只是将其转储到文件中。相反,您应该将要附加的内容Amplitude
直接写入输出文件以节省内存:
import os.path
import glob
file = glob.glob("/position/*.txt")
print file
print len(file)
for f in file:
with open(f, 'rb') as input:
all_lines = [line for line in input]
x = np.arange(1,1025) #x value is common for all the events
basename, ext = os.path.splitext(os.path.basename(f))
basename = basename[:-len('wave_1')] + 'amplitude'
with open(os.path.join(new_dir, basename + ext), 'w') as fo:
for j in range(1,1000):
y2 = np.array(all_lines[1032*j+8:1032*(j+1)],dtype=float)
x22 = list(x)
y2_=list(y2)
y22 = [((i / 4096)-0.5) for i in y2_]
min_y2 = min(y22) # Find the maximum y2 value
index_min_y2 = y22.index(min_y2) #index for minimum of y2
min_x2 = x[y22.index(min_y2)]
print 'minimum x2', min_x2, 'minimum y2', min_y2
fo.write(str(round(min_y2, 2)) + '\n')
推荐阅读
- ruby-on-rails - Rails 属于 with 包括无法识别的二阶关联
- python - 在列表字典中查找重复的字母
- php - 我会在控制器中使用 self、static、this
- spring-data - 为什么扩展 2 个其他 repo 接口的 repo 接口没有连接到控制器中?
- javascript - 如何使用 jquery 在新标签中包装与强标签同级的字符串?
- operating-system - 在上下文切换中将 CPU 分配给另一个进程究竟意味着什么?
- angular - 计算列表 Typescript 的每个元素的点击者
- d3.js - 使用 D3.js、Leaflet 或 Mapbox 用墨卡托地图包裹大圆圈
- javascript - IE array.flat() 对象不支持属性或方法'flat'
- android - 无法解决:com.google.firebase:firebase-core:16.0.5