简体   繁体   English

python删除最后一个逗号

[英]python remove last comma

I have some thing like this in output.txt file 我在output.txt文件中有这样的东西

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

output in 2nd file(output2.txt) : 第二个文件(output2.txt)中的输出:

 Service1        Service2   Servive3   Service4     Service5
 Aborted         failed     failed     Aborted      failed

Would like to remove the last comma in the line. 想删除行中的最后一个逗号。

Code I am trying: 我正在尝试的代码:

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

Use a list and append the items to it. 使用列表并将项目附加到其中。 Accessing parts[-1] returns the last item from the splitted parts. 访问零件[-1]将返回拆分零件中的最后一项。 Then use join() to put the commas in between all collected states: 然后使用join()将逗号放在所有收集的状态之间:

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

This makes the output you originally requested: 这会产生您最初请求的输出:

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

That is, the output of this code is: 也就是说,此代码的输出是:

Aborted,failed,failed,Aborted,failed

For a table view, assuming the tabbed output will line up, this code: 对于表视图,假设选项卡式输出将对齐,此代码:

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

will produce the requested table view (note there are no commas in this output): 将生成请求的表视图(注意此输出中没有逗号):

Service1        Service2   Servive3   Service4     Service5
Aborted         failed     failed     Aborted      failed

If you want to control alignment more precisely, you'll need to apply formatting, such as measuring the maximum width of text in each column and then using that as a formatting specifier. 如果要更精确地控制对齐,则需要应用格式设置,例如测量每列中文本的最大宽度,然后将其用作格式设置说明符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM