gpt4 book ai didi

python - 替换 .yml 文件中的一行的程序(PYTHON)

转载 作者:行者123 更新时间:2023-12-01 05:40:06 24 4
gpt4 key购买 nike

我正在尝试制作一个工具来替换 .yml 文件(作为文本文档打开)中的一行。我让它写入文件,但它取出所有内容并写入“固定”行。我的代码如下,以及一个实例/文件的示例。文件名很重要且无法更改。

import sys
from os import listdir

from os.path import isfile, join
onlyfiles = [ f for f in listdir() if isfile(f) and str(f)[-4:]==".yml" ] #Gets the file names, can be ANYTHING
for pos in range(1, len(onlyfiles)): #So it stops at the end of the List
with open(onlyfiles[pos], 'r') as a: #Lets open it make sure it is good
for line in a:
if line == " world: Trolling\n": # this is the target line to replace
line = line.replace(" world: Trolling", " world: world\n") #rework the line, though it wont write even if i change the R to W
with open(onlyfiles[pos], 'w') as repl: #Writes to the file, but gets rid of everything else
repl.write(line)
print(line)

未修改的文档示例:

timestamps:
login: 1373913158118
lastteleport: 1373918169442
logout: 1373918539235
kits:
trusted: 1373052268213
ipAddress: 142.165.45.129
nickname: Erin
lastlocation:
world: Trolling
x: -890.6999999880791
y: 87.0
z: -764.6999999880791
yaw: 91.99242
pitch: 75.449974
homes:
e:
world: Trolling
x: 4653.2140183238
y: 64.0
z: 80.02726116652944
yaw: 192.08363
pitch: 66.29998

我正在尝试将 100 多个文件中的“Trolling”实例替换为“world”,而不触及其他任何内容

最佳答案

当该行与此模式不匹配时,您需要在 if line == "world: Trolling\n" 之后添加一个 else 条件。还将您正在写回的所有数据放入某个变量中,并在关闭您正在读取的文件后一次将其写入最后,您无法同时读取和写入文件。

import sys
from os import listdir
from os.path import isfile, join

onlyfiles = [ f for f in listdir() if isfile(f) and str(f)[-4:]==".yml" ]

for file in onlyfiles:
wdata = ''
with open(file, 'r') as a: #Lets open it make sure it is good
for line in a:
if line == " world: Trolling\n":
line = " world: world\n" # You already know what it should be
print line
wdata += line
with open(file, 'w') as repl:
repl.write(wdata)

这样做可能更容易

for file in onlyfiles:
with open(file, 'r') as f:
d = f.read().replace('\n world: Trolling\n','\n world: world\n')
with open(file, 'w') as f:
f.write(d)

关于python - 替换 .yml 文件中的一行的程序(PYTHON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17778345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com