使用 Python 编辑文本文件 [英] edit text file using Python

查看:35
本文介绍了使用 Python 编辑文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我的 IP 地址发生变化时,我都需要更新一个文本文件,然后从 shell 运行一些命令.

I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.

  1. 创建变量 LASTKNOWN = "212.171.135.53"这是我们在编写此脚本时拥有的 IP 地址.

  1. Create variable LASTKNOWN = "212.171.135.53" This is the ip address we have while writing this script.

获取当前 IP 地址.它每天都会变化.

Get the current IP address. It will change on a daily basis.

为新 IP 创建变量 CURRENT.

Create variable CURRENT for the new IP.

比较(作为字符串)CURRENT 和 LASTKNOWN

Compare (as strings) CURRENT to LASTKNOWN

如果相同,exit()

If they are the same, exit()

如果它们不同,

A.复制"包含 LASTKNOWN IP 地址的旧配置文件 (/etc/ipf.conf) 到/tmpB. 将/tmp/ipf.conf 文件中的 LASTKNOWN 替换为 CURRENT.
C. 使用子进程mv/tmp/ipf.conf/etc/ipf.conf"
D. 使用子进程执行,"ipf -Fa -f/etc/ipf.conf"
E. 使用子进程执行,ipnat -CF -f/etc/ipnat.conf"

A. "Copy" the old config file (/etc/ipf.conf) containing LASTKNOWN IP address into /tmp B. Replace LASTKNOWN with CURRENT in the /tmp/ipf.conf file.
C. Using subprocess "mv /tmp/ipf.conf /etc/ipf.conf"
D. Using subprocess execute, "ipf -Fa -f /etc/ipf.conf"
E. Using subprocess execute, "ipnat -CF -f /etc/ipnat.conf"

exit()

我知道如何执行第 1 步到第 6 步.我陷入了文件编辑"部分,A -> C.我不知道要使用哪个模块或我是否应该就地编辑文件.有很多方法可以做到这一点,我无法决定最好的方法.我想我想要最保守的.

I know how to do steps 1 through 6. I fall down on the "file editing" part, A -> C. I can't tell what module to use or whether I should be editing the file in place. There are so many ways to do this, I can't decide on the best approach. I guess I want the most conservative one.

我知道如何使用子流程,因此您无需对此发表评论.

I know how to use subprocess, so you don't need to comment on that.

我不想替换整行;只是一个特定的虚线四边形.

I don't want to replace entire lines; just a specific dotted quad.

谢谢!

推荐答案

fileinput 模块有非常丑陋的 API,我为这个任务找到了漂亮的模块 - in_place,Python 3 示例:

fileinput module has very ugly API, I find beautiful module for this task - in_place, example for Python 3:

import in_place

with in_place.InPlace('data.txt') as file:
    for line in file:
        line = line.replace('test', 'testZ')
        file.write(line)

与文件输入的主要区别:

main difference from fileinput:

  • 不是劫持 sys.stdout,而是返回一个新的文件句柄用于写入.
  • 文件句柄支持所有标准 I/O 方法,而不仅仅是 readline().

例如 - fileinput 只能逐行编辑,in_pace 允许读取整个文件到内存(如果它不大)并修改它.

for example - fileinput can line by line editing only, in_pace allow read whole file to memory (if it not big) and modify it.

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

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