简体   繁体   中英

Modify file using python

I have files that contains the following lines:

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

I need to find the id value, then based on simple condition modify(add/subtract some number from the value) that number and write file back. My attempt is:

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

here I am thinking to capture 3 parts of line char id= , value and the rest of line. Then modify value and create new string. But I doubt it's effective way in Python. Also I'm not sure if there is a way to work on same file instead of creating new file, deleting old and renaming back to old name in order to modify file content.

You'll have to replace the file (so write to a temporary file). However, the fileinput module makes this easy for you:

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)

This example simply increments the id value by 1, you can adjust the code to do whatever you want with the id_ integer.

By specifying inplace=True , the fileinput module will move the original file to a backup, capture anything you write to stdout , and write it to original file location instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM