Python:读取和写入文件,并使用函数修改它们

时间:2016-06-09 08:20:09

标签: python function file-io

我有一个名为Energy_vs_volume.dat的文件,如下所示:

 # volume    energy   
    64       -180.001   
    63       -180.002
    62       -180.005
     .        .
     .        .
     .        .

我已经编写了一个名为calculate.py的python脚本,其中包含一个函数。 我想修改名为calculate.py的python脚本,以便执行以下操作:

1)阅读Energy_vs_volume.dat文件

2)进行此计算:获取Energy_vs_volume.dat文件的第1列,即“卷”列,并将其视为变量V的数据。

3)我已在calculate.py脚本中定义了此功能:

E0=-180.00
B0=55
V0=120 
B0_prime=20

def P(V): 
   f0=(3.0/2.0)*B0
   f1=((V0/V)**(7.0/3.0))-((V0/V)**(5.0/3.0))
   f2=((V0/V)**(2.0/3.0))-1
   pressure= f0*f1*(1+(3.0/4.0)*(B0_prime-4)*f2)
   return pressure 

4)我需要从Energy_vs_volume.dat文件(V的值)向函数提供第1列的值,并创建另一个名为{{1}的文件那将包含:

Pressure_vs_volume.dat

5)然后我需要创建一个名为 # volume pressure 64 the calculated value 63 the calculated value 62 the calculated value . . . . . . 的文件,其中包含:

5a)第一列:Energy_vs_pressure.dat文件中第二列的数据

5b)第二列:Pressure_vs_volume.dat文件中第二列的数据:

Energy_vs_volume.dat

如果你能帮助我,我将不胜感激

编辑

如果# pressure energy the calculated value -180.001 the calculated value -180.002 the calculated value -180.005 . . . . . . 有第3列名为Energy_vs_volume.dat

# velocity

我运行相同的脚本,但是这行:

# volume energy velocity 64 -180.001 25 63 -180.002 21 62 -180.005 22 . . . . . . . . .

它无法分裂,给出了这个错误:

volume, energy, velocity = [float(n) for n in line.split()]

1 个答案:

答案 0 :(得分:1)

希望这是可以理解的。

# open the files
volume_energy = open('Energy_vs_volume.dat')
volume_pressure = open('Pressure_vs_volume.dat', 'w') # w for writing
pressure_energy = open('Energy_vs_pressure.dat', 'w') # w for writing

# write first lines of your created files
# (still not sure about the exact formatting)
# \t is a tab, \n is a newline
volume_pressure.write('# volume\tpressure\n')
pressure_energy.write('# pressure\tenergy\n')

with open('Energy_vs_volume.dat') as energy_volume: # open the file
    energy_volume.next() # skip the first line
    for line in energy_volume: # iterate over the remaining lines
        # split the lines (removes linebreaks, tabs and spaces)
        # convert all items to floats, unpack the list into two variables
        volume, energy = [float(n) for n in line.split()]
        pressure = P(volume) # call your function
        # write values to files
        # (still not sure about the exact formatting)
        volume_pressure.write('{}\t{}\n'.format(volume, pressure))
        pressure_energy.write('{}\t{}\n'.format(pressure, energy))

# close files
volume_energy.close()
volume_pressure.close()
pressure_energy.close()

Energy_vs_volume.dat包含

# volume    energy
64  -180.001
63  -180.002
62  -180.005

程序创建一个包含

的文件Pressure_vs_volume.dat
# volume    pressure
64.0    887.265477926
63.0    963.895750396
62.0    1047.46825523

和包含

的文件Energy_vs_pressure.dat
# pressure  energy
887.265477926   -180.001
963.895750396   -180.002
1047.46825523   -180.005