簡體   English   中英

傳遞變量以python中的字符串形式循環

[英]passing variable to loop as string in python

我有一個python腳本,它將每個文件放在目錄中,遍歷文件的內容並為每個輸入文件創建一個輸出文件。 此輸出文件可能具有重復的條目,如果確實如此,我只想采用類似於UNIX命令的唯一值

uniq -u input.file > output.file

盡管我可以使用Shell腳本來執行此操作,但我還是希望包含一行僅采用唯一值的python。 我知道我可以這樣做:

import os
os.system("uniq -u input.file > output.file")

但是,當我嘗試將其循環放置時,它將使我剛剛制作的所有文件都變得唯一:

for curfile in fs:
    if curfile[-3:]=='out':
        os.system("uniq -u %s > %s") % (str(curfile), str(curfile[:-4] + ".uniq")

我收到以下錯誤:

unsupported operand type(s) for %: 'int' and 'tuple'

我嘗試了幾種語法來嘗試識別變量,但在網絡上找不到足夠類似的示例。 任何建議將不勝感激。

你有

os.system(
             "uniq -u %s > %s"
         ) % ( # The % and this paren should be inside the call to os.system
                 str(curfile), 
                 str(curfile[:-4] + ".uniq")
               # you're missing a close paren here

你需要

os.system(
             "uniq -u %s > %s" % (
                                     str(curfile), 
                                     str(curfile[:-4] + ".uniq")
                                 )
         )

首先,對字符串進行格式化, 然后將其轉到os.system -現在,將其轉到os.system然后嘗試對結果進行%設置,即int uniq的返回碼。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM