如何使用python

时间:2019-06-18 13:15:45

标签: python-3.x

我刚刚开始学习python,并尝试创建一些小的项目供我学习。想知道是否有任何方法可以编辑“ .properties”文件中的值。这是文件外观的一小段。

broadcast-rcon-to-ops=true
view-distance=10
max-build-height=256
server-ip=
level-seed=
rcon.port=25575

设法更改值,但只能在该instance(?)本身内更改,而不能更改实际文件中的值

#placeholder values
file_location = 'server.properties'
property = 'max-build-height'
new_value = '300'

properties_dict = {}
fileObj = open(file_location)
for line in fileObj:
    line = line.strip()
    key_value = line.split('=')
    if len(key_value) == 2:
        properties_dict[key_value[0]] = key_value[1]

#testing purposes
x = properties_dict[property]
print(property + " = " + x)
properties_dict[property] = new_value
x = properties_dict[property]
print("new " + property + " = " + x)

我想改为更改属性文件中的值,我该如何去做?属性文件中的before / after的示例为

之前

broadcast-rcon-to-ops=true
view-distance=10
max-build-height=256
server-ip=
level-seed=
rcon.port=25575

之后

broadcast-rcon-to-ops=true
view-distance=10
max-build-height=300
server-ip=
level-seed=
rcon.port=25575

预先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

下面的代码应该可以工作。从属性中创建字典,然后使用键对值进行更改,然后将其写入同一文件。

from collections import OrderedDict

file_location = 'input_file.txt'

prop_key, prop_value = 'max-build-height', 300

props = OrderedDict(line.rstrip().split('=', 1)
                    for line in open(file_location))

props[prop_key] = prop_value
with open(file_location, 'w') as fpw:
    for prop, value in props.items():
        fpw.write(f'{prop}={value}\n')

输出:

broadcast-rcon-to-ops=true
view-distance=10
max-build-height=300
server-ip=
level-seed=
rcon.port=25575