2017-08-27 62 views
0

我試圖替換文件中的第一個字符,以便最終得到其中的10。這裏是我的代碼:替換文件Python 2.7中的第一個字符

import os 

hostName = raw_input("IP: ") 
communicate = open("communicate.txt", "w") 

while True: 
    response = os.system("ping " + hostName + " -c 1") 
    if response == 0: 
     # Replace first character with '1' 
    else: 
     # Replace first character with '0' 

我正在通過終端在Linux虛擬機中運行代碼。

+3

用'「w」'打開文件後,它已被覆蓋。 –

+1

'communications.txt'文件是否爲空?如果不是,你想保留它的內容(除了第一個字符)? –

回答

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的情況下將其刪除。

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() 
0

如果您希望保留的文件的內容,並替換第一個字符,
在一個變量,你可以簡單地read文件,保存其內容(不包括第1個字符),
然後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) 

如果你想保持替換第1個字符, 那麼你需要continuesly覆蓋您的文件。
我會建議如果這是一些檢查,讓代碼在您的while循環的每次迭代中睡眠幾秒鐘,使用函數從time模塊 我希望我幫助!

相關問題