簡體   English   中英

python刪除最后一個逗號

[英]python remove last comma

我在output.txt文件中有這樣的東西

Service1:Aborted
Service2:failed
Service3:failed
Service4:Aborted
Service5:failed

第二個文件(output2.txt)中的輸出:

 Service1        Service2   Servive3   Service4     Service5
 Aborted         failed     failed     Aborted      failed

想刪除行中的最后一個逗號。

我正在嘗試的代碼:

    file=open('output.txt','r')
    target=open('output2.txt','w')
    for line in file.readlines():
          line=line.strip()
          parts=line.split(":")
          for part in parts:
               var2=part.strip()+","
          target.write(var2.rstrip(','))        # Not working
   target.close()

使用列表並將項目附加到其中。 訪問零件[-1]將返回拆分零件中的最后一項。 然后使用join()將逗號放在所有收集的狀態之間:

states = []
for line in file.readlines():
    parts=line.strip().split(':')
    states.append(parts[-1])
print(','.join(states))

這會產生您最初請求的輸出:

file=open('output.txt','r')
target=open('output2.txt','w')
states = [line.strip().split(':')[-1] for line in file.readlines()]
target.write(','.join(states))
target.close()

也就是說,此代碼的輸出是:

Aborted,failed,failed,Aborted,failed

對於表視圖,假設選項卡式輸出將對齊,此代碼:

file=open('output.txt','r')
target=open('output2.txt','w')
states, titles = [], []
for line in file.readlines():
    title, state = line.split(':')
    titles.append(title)
    states.append(state)
target.write('\t'.join(titles))
target.write('\n')
target.write('\t'.join(states))
target.close()

將生成請求的表視圖(注意此輸出中沒有逗號):

Service1        Service2   Servive3   Service4     Service5
Aborted         failed     failed     Aborted      failed

如果要更精確地控制對齊,則需要應用格式設置,例如測量每列中文本的最大寬度,然后將其用作格式設置說明符。

暫無
暫無

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

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