![](/img/trans.png)
[英]How to use the output from glob.glob to read the outputted file?
[英]How to write multiple output text file from multiple input text file with different name by using glob.glob in python?
我是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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.