使用python修改文件 [英] Modify file using python

查看:54
本文介绍了使用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

我需要找到 id 值,然后根据简单的条件修改(从值中添加/减去一些数字)该数字并将文件写回.我的尝试是:

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: 

在这里我想捕获行 char id= 的 3 部分,值和行的其余部分.然后修改值并创建新字符串.但我怀疑它在 Python 中是否有效.此外,我不确定是否有办法处理同一个文件,而不是创建新文件、删除旧文件并重命名回旧名称以修改文件内容.

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.

推荐答案

您将替换文件(因此写入临时文件).但是,fileinput 模块 使这对您来说很容易:

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)

这个例子只是将 id 值增加 1,你可以调整代码以使用 id_ 整数做任何你想做的事情.

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

通过指定 inplace=Truefileinput 模块会将原始文件移动到备份,捕获您写入 stdout 的任何内容,以及改为将其写入原始文件位置.

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.

这篇关于使用python修改文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆