将值从txt添加到csv新列

时间:2018-06-06 03:44:28

标签: python csv

我希望test.txt中的数据添加到result.csv的“Results”列下。 我怎样才能完成任务?我尝试了很多方法,但我无法完成。

顺便说一句,如果两个“Running Image”可以在一个单元格中,那将会很棒。该行应为“version”。

的test.txt

Running Image: SMM_2x10G 
Running Image: SMM_2x10G
C100G
SystemUptime:1d,19h,40m,30s
CPU utilization is normal with 96.1 idle
Memory is with good with 50.00%

result.csv

Content                 Results
Version 
Product
System Uptime   
CPU status  
MemFree/MemTotal    

最终结果应该是这样的:

Content            Results
Version "          Running Image: SMM_2x10G 
                   Running Image: SMM_2x10G"
Product            C100G
System Uptime      SystemUptime:1d,19h,40m,30s
CPU status         CPU utilization is normal with 96.1 idle
MemFree/MemTotal   Memory is with good with 50.00%

提前谢谢!

我想我找到了一种方法: 代码如下:

import pandas,sys
import pandas as pd
df1=pd.read_csv('result.csv')
df2=pd.read_csv('test.csv')
df3=pd.concat([df1,df2],axis=1)
print(df3)
with open('test-result.csv','w',encoding="utf-8") as f:
    df3.to_csv(f,index=False)

然后我查看了我以前的代码并遇到了问题。实际上,test.csv是从包含大量数据的日志文件中提取的。我用“for ... if ..” 得到想要的数据。如果在日志中找不到数据,我希望它最终在“test.csv”中打印一个空白行,但是对于“for ... if ... else”,我有很多空白行.... ..

for line in fp:
      if "Unknown(255) Unknown" in line:
            Unknown = line_stream
            print("The module is in unknown status %s:" % line_stream, file=fp1)
      else:
            print("\n",file=fp1)

知道如何通过谷歌解决...... Thx。

1 个答案:

答案 0 :(得分:0)

找到方法:

import pandas,sys
import pandas as pd
df1=pd.read_csv('result.csv')
df2=pd.read_csv('test.csv')
df3=pd.concat([df1,df2],axis=1)
print(df3)
with open('test-result.csv','w',encoding="utf-8") as f:
    df3.to_csv(f,index=False)