0

So I have a file that looks like this

mass (GeV) spectrum (1-100 GeV)

10 0.06751019803888393

20 0.11048827045815585

30 0.1399367785958526

40 0.1628781532692572

I want to multiply the spectrum by half or any percentage, then create a new file with the same data, but the spectrum is replaced with the new spectrum multiplied by the multiplier

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))

The problem I'm having is f.replace(Spectrum,Spectrumnew) is not working, and if I were to comment it out, a new file is created called test.txt with just Spectrumnew nothing else. What is wrong with f.replace, am I using the wrong string method?

Enrique92
  • 55
  • 6
  • I would recommend to use a csv parser. Delimiter is a space in your case. Docs: https://docs.python.org/3/library/csv.html – bb1950328 Jun 11 '20 at 06:31

1 Answers1

0

replace is a function that works on strings. f is not a string. (For that matter, neither is Spectrum or Spectrumnew.)

You need to construct the line you want in the output file as a string and then write it out. You already have string output working. To construct the output line, you can just concatenate the first number from the input, a tab character, and the product of the second number and the multiplier. You can convert a number to a string with the str() function and you can concatenate strings with the + operator.

There are several more specific answers on this site already that may be helpful, such as replacing text in a file with Python.

Dennis Sparrow
  • 938
  • 6
  • 13