[英]Editing a column by a multiplier, and then replacing the column with the multiplier and saving the file as a new .txt file -python
所以我有一個看起來像這樣的文件
質量 (GeV) 譜 (1-100 GeV)
10 0.06751019803888393
20 0.11048827045815585
30 0.1399367785958526
40 0.1628781532692572
我想將光譜乘以一半或任何百分比,然后使用相同的數據創建一個新文件,但光譜被乘以乘數的新光譜替換
DM_file=input("Name of DM.in file: ") #name of file is DMmumu.in
print(DM_file)
n=float(input('Enter the percentage of annihilation: '))
N=n*100
pct=(1-n)
counter = 0
with open (DM_file,'r+') as f:
with open ('test.txt','w') as output:
lines=f.readlines()
print(type(lines))
Spectrumnew=[]
Spectrum=[]
for i in range(8,58):
single_line=lines[i].split("\t")
old_number = single_line[1]
new_number = float(single_line[1])*pct
Spectrumnew.append(new_number)
Spectrum.append(old_number)
f.replace(Spectrum,Spectrumnew)
output.write(str(new_number))
我遇到的問題是 f.replace(Spectrum,Spectrumnew) 不起作用,如果我將其注釋掉,則會創建一個名為 test.txt 的新文件,而只有 Spectrumnew 沒有其他內容。 f.replace 有什么問題,我使用了錯誤的字符串方法嗎?
replace
是一個適用於字符串的 function。 f
不是字符串。 (就此而言, Spectrum
或Spectrumnew
都不是。)
您需要在 output 文件中將您想要的行構造為字符串,然后將其寫出來。 您已經有字符串 output 工作。 要構造 output 行,您只需連接輸入中的第一個數字、制表符以及第二個數字與乘數的乘積。 您可以使用str()
function 將數字轉換為字符串,並且可以使用+
運算符連接字符串。
該站點上已經有幾個更具體的答案可能會有所幫助,例如用 Python 替換文件中的文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.