替换文件Python 2.7中的第一个字符

时间:2017-08-27 12:43:19

标签: python python-2.7 file

我尝试替换文件中的第一个字符,以便最终使用npm install -g tsd@latest 1。这是我的代码:

0

我正在通过终端在Linux虚拟机中运行代码。

3 个答案:

答案 0 :(得分:0)

import os

hostName = raw_input("IP: ")
communicate = open("communicate.txt", "r+")
while True:
    response = os.system("ping " + hostName + " -c 1")
    if response == 0:
        text = communicate.read()
        communicate.write(str(1) + text[1:])
    else:
        text = communicate.read()
        communicate.write(str(0) + text[1:])
 communicate.close()

答案 1 :(得分:0)

如果您希望保留文件的内容,并替换第一个字符,您只需read该文件,将其内容(不包括第一个字符)保存在变量中,
/>然后write在覆盖的文件中,如下:

import os

hostName = raw_input("IP: ")

with open("communicate.txt", "r") as f:
    content = f.read()[1:]

while True:
    response = os.system("ping " + hostName + " -c 1")
    if response == 0:
        with open("communicate.txt", "w") as communicate:
            comunicate.write('1' + content)
    else:
        with open("communicate.txt", "w") as communicate:
            comunicate.write('0' + content)

如果你想继续更换第一个角色, 然后你需要继续覆盖你的文件 我建议如果这是一些检查,请使用while模块中的sleep函数让代码在time循环的每次迭代中休眠几秒钟 我希望我能帮忙!

答案 2 :(得分:0)

这似乎可以满足您的需求:

import os
import time

hostName = raw_input("IP: ")
communicateFd = os.open("communicate.txt", os.O_CREAT | os.O_RDWR)
communicate = os.fdopen(communicateFd, 'r+b')

while True:
    communicate.seek(0)
    response = os.system("ping " + hostName + " -c 1")
    if response == 0:
        communicate.write('1')
    else:
        communicate.write('0')
    time.sleep(1)

communicate.close()

正如其他人所说,使用模式'w'打开会截断文件,破坏以前的内容(如果有的话)。

使用os模块,我们可以更好地控制文件的打开方式。在这种情况下,只有在它不存在时才创建,然后以读/写模式打开。

在循环的顶部我们seek到文件的开头,允许我们根据需要简单地重写第一个字节。

添加了一个sleep语句以防止这种情况发生紧急循环,但可以在不影响文件I / O的情况下删除它。