簡體   English   中英

使用python修改文件

[英]Modify file using python

我的文件包含以下幾行:

info face="asd" size=49 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=0,0
common lineHeight=52 base=43 scaleW=128 scaleH=128 pages=1 packed=0
page id=0 file="asd.png"
chars count=9
char id=32 x=58 y=82 width=0 height=0 xoffset=0 yoffset=40 xadvance=9 page=0 chnl=0
char id=179 x=34 y=42 width=28 height=38 xoffset=2 yoffset=6 xadvance=26 page=0 chnl=0
char id=181 x=94 y=2 width=28 height=38 xoffset=2 yoffset=6 xadvance=26 page=0 chnl=0
char id=183 x=2 y=42 width=30 height=38 xoffset=2 yoffset=6 xadvance=27 page=0 chnl=0
char id=185 x=2 y=2 width=30 height=38 xoffset=2 yoffset=6 xadvance=27 page=0 chnl=0
char id=187 x=64 y=2 width=28 height=38 xoffset=2 yoffset=6 xadvance=26 page=0 chnl=0
char id=189 x=34 y=2 width=28 height=38 xoffset=2 yoffset=6 xadvance=26 page=0 chnl=0
char id=191 x=34 y=82 width=22 height=36 xoffset=2 yoffset=8 xadvance=18 page=0 chnl=0
char id=193 x=2 y=82 width=28 height=38 xoffset=2 yoffset=6 xadvance=26 page=0 chnl=0
kernings count=0

我需要找到id值,然后根據簡單條件修改(從值中減去/減去一些數字)然后將該文件寫回。 我的嘗試是:

input = open('file.txt', 'r')
for line in input: 

在這里,我正在考慮捕獲char id= ,行值和行的其余部分的3部分。 然后修改值並創建新的字符串。 但是我懷疑它在Python中是否有效。 另外,我不確定是否有辦法處理同一文件而不是創建新文件,刪除舊文件並重命名為舊文件以修改文件內容。

您將不得不替換該文件(因此要寫入一個臨時文件)。 但是, fileinput模塊使您更容易:

import fileinput
import sys

for line in fileinput.input(filename, inplace=True):
    if line.startswith('char id='):
        _, id_, rest = line.split(None, 2)
        id_ = int(id_.split('=')[1])
        id_ += 1  # adjust as needed
        line = 'char id={} {}'.format(id_, rest)

    sys.stdout.write(line)

本示例僅將id值增加1,就可以使用id_ integer調整代碼以執行所需的任何操作。

通過指定fileinput inplace=Truefileinput模塊會將原始文件移動到備份中,捕獲您寫入到stdout ,然后將其寫入原始文件位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM