2015-09-03 35 views
-2

我想寫一個腳本,刪除包含一個字符串的行,並保持行包含另一個。我想最後我有一個縮進錯誤,誰能看到如何解決這個問題?Python:創建一個文件,其中包含一個特定的字符串,不包含另一個特定的字符串

import os 
import sys 

#Reading Input file 
f = open(sys.argv[1]).readlines() 

for line in f: #(read line 0 to last line of input file) 
if 'Futures' in line and 'Elec' not in line: #if string "Futures" is not there in dictionary i.e it is unique so store it into a dictionary 
#f = open("C://Python27//New_File.csv", 'w') 
#f.close() 
#opens and close new file 
nf = open("C://Python27//New_File.csv", "w") 
nf.write(data) 
nf.close() 
+3

「我認爲我最後有一個縮進錯誤」是的,我同意。錯誤是你根本沒有縮進。 – Kevin

+0

你有不止一個,你也將每次用'w'打開時全部覆蓋。 –

回答

-1

試試這個:

for line in f: 
    if 'Futures' in line and 'Elec' not in line: 
     nf = open("C://Python27//New_File.csv", "a") 
     nf.write(data) 
     nf.close() 
+0

感謝所有人的貢獻,只是稍微移動一下,是否可以檢查一個指定列中是否存在某個值? –

+0

你的意思是1列中的1個字符? –

+0

嗨安東尼,不,我的意思是1字符串例如出現在特定的列字段,而不是檢查整個行。 –

0

你的壓痕和邏輯都錯了,如果你繼續與w開放,你會最終有一個單一的線,你需要打開輸出文件一旦外循環寫,因爲你去:

import sys 

#Reading Input file 
with open(sys.argv[1]) as f, open("C://Python27//New_File.csv", "w") as out: 
    for line in f: #(read line 0 to last line of input file) 
     if 'Futures' in line and 'Elec' not in line: #if string "Futures" is not there in dictionary i.e it is unique so store it into a dictionary 
      out.write(line) 

你也可以遍歷文件對象,也沒有必要和理由,除非你真正需要的行列表使用readlines方法。

另一方面,您可能需要處理傳遞文件不存在或您無權讀取的情況。

相關問題