2016-05-23 35 views
1

我是python的新手,剛開始學習基礎知識。使用python評論文本文件中的某些行

我試圖創建一個程序,將文件和評論(使用#)在等號後沒有任何內容的行。

例如,

V12 =

V13 = 3

應該是

#V12 =

V13 = 3

預先感謝您的幫助。

回答

1

這樣的事情我會保持它的簡單,並從一個文件中讀取和寫入到另一個。

with open('/path/to/myfile') as infile: 
    with open('/path/to/output', 'w') as outfile: 
     for line in infile: 
     if line.rstrip().endswith('='): 
      outfile.write('#' + line + '\n') 
     else: 
      outfile.write(line + '\n') 
2

基本上,你需要閱讀文件。然後,檢查每一行。如果該行在等號後分割了某些內容,則按原樣輸出該行;否則,將hashtag附加到前面,然後輸出該行。

f = open(filename, "r") 
lines = f.readlines() 
f.close() 

output_lines = [] 
for line in lines: 
    if len(line.split("=")[1]) > 0: 
     output_lines.append(line) 
    else: 
     output_lines.append("#" + line) 
f = open("commented" + filename, "w") 
f.write("\n".join(output_lines)) 
f.close() 
1

下面是一些代碼,你可以運行像:

python comment.py <infile> outfile 

comment.py:

import sys 

# stdin/stdout live in sys 
# "for line in file" reads each line of the file, returning the text 
# of the line including the trailing newline 
for line in sys.stdin: 
    if line.strip().endswith('='): 
     line = "#" + line 
    # print command adds a trailing newline, so we have to use all but 
    # the last character of our input line 
    print(line[:-1]) 

你可以得到很多發燒友使用re模塊的正則表達式。

鑑於INFILE:

V12 = 'hello' 
V23 = 'world' 
V34 = 

生產:

V12 = 'hello' 
V23 = 'world' 
#V34 = 
+0

是的。沒有讀過這個問題。將解決。 – Neapolitan

+0

@mattsap,這是更好嗎? – Neapolitan

0

您也可以使用此代碼來完成您的任務。唯一的限制是空變量沒有空白標識。例如。 'v1 ='

MyFile=open("AFile.txt", 'r+'); 
newdata = [] 
data = MyFile.readlines() 
for item in data: 
    PosEquals = item.find('=') 
    LenOfItem = len(item) 
    # Checks position of equals in line 
    # and also if there is anything after equal sign 
    if PosEquals <> -1 and PosEquals <> LenOfItem-1: 
     newdata.append(item) 
    else: 
     newdata.append('#'+item) 
MyFile.seek(0) 
MyFile.writelines(newdata)  
MyFile.close() 
0

謝謝你的幫助。

這裏的問題是,你的程序中的「#」之後的任何東西都被認爲是評論,是否有任何方法來在python中轉義「#」?

再次感謝您

相關問題