[英]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.