简体   繁体   English

使用python修改文件

[英]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. 我需要找到id值,然后根据简单条件修改(从值中减去/减去一些数字)然后将该文件写回。 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. 在这里,我正在考虑捕获char id= ,行值和行的其余部分的3部分。 Then modify value and create new string. 然后修改值并创建新的字符串。 But I doubt it's effective way in Python. 但是我怀疑它在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: 但是, 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)

This example simply increments the id value by 1, you can adjust the code to do whatever you want with the id_ integer. 本示例仅将id值增加1,就可以使用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. 通过指定fileinput inplace=Truefileinput模块会将原始文件移动到备份中,捕获您写入到stdout ,然后将其写入原始文件位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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