![](/img/trans.png)
[英]Looking to a build a simple find and replace program for file paths using Python
[英]Find and replace variable value in a .py file using another python program
这是我的挑战。 我有一个 radioConfig.py 文件,其中包含在用户更改位置或扫描时间时需要更改的变量值。 这将与学生一起使用,所以我正在编写一个 GUI pysimplegui 来更改这些变量的值。
这是我到目前为止所拥有的,但它不起作用。 它替换了变量名,而不是值。
我正在使用 Rpi 和 python3。 我学过电子学,我的编程技能是 C。 我不确定这是否是解决我的挑战的最佳方法,也不知道存在的可能有用的 python 选项。 任何帮助都会很棒。
#File: GuiTest.py before code is executed
freqCenter = 21000000
freqBandwidth = 8000000
upconvFreqHz = 125000000
fftWindow = "BlacHarr"
notes = "Test"
rtlSampleRateHz = 2000000
#-----------------------------------------------------------------------
#Program which will be a gui asking user for input values
freqCenterGUI = 20800280
with open('GuiTest.py', 'r') as file :
filedata = file.read()
filedata = filedata.replace('freqCenter', str(freqCenterGUI).strip('()'))
with open('GuiTest.py', 'w') as file:
file.write(filedata)
#File: GuiTest.py after code is executed
20800280 = 21000000
freqBandwidth = 8000000
upconvFreqHz = 125000000
notes = "Test"
rtlSampleRateHz = 2000000
#-----------------------------------------------------------------------
我会说:使用配置文件。
修改脚本真的不是一个好习惯!
在您的 cfg.ini 中:
[_]
freqCenter = 21000000
freqBandwidth = 8000000
upconvFreqHz = 125000000
fftWindow = BlacHarr
notes = Test
rtlSampleRateHz = 2000000
然后使用 configparser:
import configparser
cfg = configparser.ConfigParser()
with open('cfg.ini', encoding='utf-8') as f:
cfg.read_file(f)
cfg['_']['freqCenter'] = '20800280'
with open('cfg.ini', 'w', encoding='utf-8') as f:
cfg.write(f)
编辑:
或者,正如@juanpa.arrivillaga 所建议的,使用 json 也是一个很好的解决方案!
口味问题... :)
又快又脏:
文件 1:
freqCenter = 21000000
freqBandwidth = 8000000
upconvFreqHz = 125000000
fftWindow = "BlacHarr"
notes = "Test"
rtlSampleRateHz = 2000000
文件 2
#Program which will be a gui asking user for input values
freqCenterGUI = "20800280"
my_dict={}
file_data=open("GuiTest.py", "r")
in_lines=file_data.readlines()
for line in in_lines:
var, val = line.split('=')
if var.strip() == "freqCenter":
val = freqCenterGUI + "\n"
my_dict[var]=val
f_out=open("GuiTest.py", "w")
for key,val in my_dict.items():
f_out.write(str(key)+"="+str(val))
f_out.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.