【问题标题】:with python from csv to text files用python从csv到文本文件
【发布时间】:2020-09-16 07:10:42
【问题描述】:

我正在尝试从 csv 文件中写入两个 txt 文件( Test_8.txt 和 Test_9.txt )。 从第 COL4 行开始,我得到单引号和双引号以及 '['。

我怎样才能摆脱它们?

csvfie:

NR;COL1;COL2;COL3;COL4;COL5;COL6;COL7;REMARK

Test_9;96;0;4.26;4;5.25;-0.01;1;Test_9 tested, python

Test_9;96;0;4.26;4;11.75;2.35;1;Test_9 tested, python

Test_9;96;0;4.26;4;-3;-3;0.9;Test_9 tested, python

Test_8;95;0;4.25;3;4.75;-0.11;1;Test_8 tested, python

Test_8;95;0;4.25;3;-3;-3;0.9;Test_8 tested, python

Test_8;95;0;4.25;3;16.5;4.26;1;Test_8 tested, python

Test_8;95;0;4.25;3;12.751;2.861;1;Test_8 tested, python

预期输出:

TYPE    1.0
NR  Test_8

COL1    95

COL2    0
COL3    4.250

COL4    3  
-3.000  -3.000  0.900
4.750   -0.110  1.000
12.751  2.861   1.000
16.500  4.260   1.000

REMARK
Test_8 tested
with python

我的代码:

import os
import pandas as pd
pd.options.mode.chained_assignment = None 
df=pd.read_csv(r'C:\Users\Desktop\test_map\test\mycsv_v1.csv',sep=';',index_col='NR')

df['COL3'] = df['COL3'].map('{:,.3f}'.format)

df['COL5'] = df['COL5'].map('{:,.3f}'.format)
df['COL6'] = df['COL6'].map('{:,.3f}'.format)
df['COL7'] = df['COL7'].map('{:,.3f}'.format)

ans = [[x,pd.DataFrame(y)] for x, y in df.groupby(df.index, as_index=True)]
#print ans

for table in ans:
    line1=table[1].iloc[0]
    #print line1
    line1['TYPE']=1.0
    line1['NR']=table[0]

    col567=table[1][['COL5','COL6','COL7']].sort_values(by=['COL5'], ascending=True)
    print col567

    for row in range(len(col567)):
        #print row
        line1[str(col567.values[row])[1:-1]] = None

    line1['']=None

    col8=table[1]['REMARK'].str.split(',')[0]
    col8=table[1]['REMARK'].str.split(', ')[1]
    line1['REMARK']=str(col8.values[0])
    line1['REMARK']=str(col8.values[1])


    line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4', 
             str(col567.values[0:]), '', 'REMARK\n', col8.values[0],col8.values[1]]]


    line1.to_csv(table[0]+'.txt',sep='\t')

我的输出;

TYPE    1.0
NR  Test_8

COL1    95

COL2    0

COL3    4.250
COL4    3
"[['-3.000' '-3.000' '0.900']
 ['12.751' '2.861' '1.000']
 ['16.500' '4.260' '1.000']
 ['4.750' '-0.110' '1.000']]"   

"REMARK
"   
Test_8 tested   
python  

【问题讨论】:

  • 您应该将当前输出添加到问题中。
  • 有点不清楚您要达到的目标,您可以继续添加有关要从 CSV 提取到相应 txt 文件的部分的详细信息
  • @xvan 谢谢我已经添加了我的输出
  • 不要使用str(),而是创建更复杂的代码来将列表转换为字符串。
  • @rohitkeshav,是的,我的目标是从 csv 中获取两个 txtfile(Test_8.txt 和 Test_9.txt)

标签: python python-3.x pandas python-2.7 csv


【解决方案1】:

如果您想要没有[]quota 的文本,则不要使用str() 和默认格式,而是创建自己的函数来格式化它。您可以为此使用" ".join()for-loop

示例代码

import numpy as np

data = np.array([['-3.000', '-3.000', '0.900'],
 ['12.751', '2.861', '1.000'],
 ['16.500', '4.260', '1.000'],
 ['4.750', '-0.110', '1.000']])

print('--- default format ---')
text = str(data)
print(text)

print('--- own format ---')
text = ''
for row in data:
    text += ' '.join(row) + '\n'
print(text)

结果:

--- default format ---
[['-3.000' '-3.000' '0.900']
 ['12.751' '2.861' '1.000']
 ['16.500' '4.260' '1.000']
 ['4.750' '-0.110' '1.000']]

--- own format ---
-3.000 -3.000 0.900
12.751 2.861 1.000
16.500 4.260 1.000
4.750 -0.110 1.000

顺便说一句:你需要转换col567.values[0:]

print(str(col567.values[0:]))

text = ''
for row in col567.values[0:]:
    text += " ".join(row) + '\n'
print(text)

并在

中使用这个text
line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4', 
         text, '', 'REMARK\n', col8.values[0],col8.values[1]]]

我试图运行你的代码,但它有很多错误,而且永远无法运行。


使用字符串格式化的示例代码

我使用io.StringIO 仅用于模拟带有数据的文件,但您使用pd.read_csv

顺便说一句:我不得不更改一些元素,因为要获得正确排序的数据,它们必须是整数/浮点值而不是字符串 {:,.3f}

import os
import pandas as pd

pd.options.mode.chained_assignment = None 

#df=pd.read_csv(r'C:\Users\Desktop\test_map\test\mycsv_v1.csv',sep=';',index_col='NR')

text = u'''NR;COL1;COL2;COL3;COL4;COL5;COL6;COL7;REMARK
Test_9;96;0;4.26;4;5.25;-0.01;1;Test_9 tested, python
Test_9;96;0;4.26;4;11.75;2.35;1;Test_9 tested, python
Test_9;96;0;4.26;4;-3;-3;0.9;Test_9 tested, python
Test_8;95;0;4.25;3;4.75;-0.11;1;Test_8 tested, python
Test_8;95;0;4.25;3;-3;-3;0.9;Test_8 tested, python
Test_8;95;0;4.25;3;16.5;4.26;1;Test_8 tested, python
Test_8;95;0;4.25;3;12.751;2.861;1;Test_8 tested, python'''

import io
df = pd.read_csv(io.StringIO(text), sep=';', index_col='NR')

df['COL3'] = df['COL3'].map('{:,.3f}'.format)
#df['COL5'] = df['COL5'].map('{:,.3f}'.format)
#df['COL6'] = df['COL6'].map('{:,.3f}'.format)
#df['COL7'] = df['COL7'].map('{:,.3f}'.format)

ans = df.groupby(df.index, as_index=True)

for table in ans:
    line1 = table[1].iloc[0]

    col567 = table[1][['COL5','COL6','COL7']].sort_values(by=['COL5'], ascending=True)
    col567_text = '\n'.join(' '.join('{:,.3f}'.format(item) for item in row) for row in col567.values[0:])        

    col8 = table[1]['REMARK'][0].split(', ')

    text = '''TYPE    {type_}
NR  {nr}

COL1    {col1}

COL2    {col2}
COL3    {col3}

COL4    {col4}
{col567}

REMARK
{remark1}
{remark2}'''.format(
    type_ = 1.0,
    nr = table[0],
    col1 = table[1]['COL1'][0],
    col2 = table[1]['COL2'][0],
    col3 = table[1]['COL3'][0],
    col4 = table[1]['COL4'][0],
    col567 = col567_text,
    remark1 = col8[0],
    remark2 = col8[1],
)    


    print(text)

    with open(table[0]+'.txt', 'w') as f:
        f.write(text)

【讨论】:

  • 谢谢你,我明白你的意思了,但我不知道在哪里以及如何在我的脚本中使用它?你能把它改成我的脚本吗?
  • 使用print()查看变量中的内容 - 您将看到哪个有需要更改的数据,然后以自己的格式分配数据。
  • 可能你必须改变str(col567.values[0:]) - 检查print( str(col567.values[0:]) )
  • @furas 我得到这个结果“TYPE 1.0 NR Test_8 COL1 95 COL2 0 COL3 4.250 COL4 3 “COL5 COL6 COL7” “REMARK” Test_8 测试 python
  • 我需要获取 COL5、COL6 和 COL7 的值。但我不明白
【解决方案2】:

您正在打印一个由 numpy.arrays 组成的 numpy.array。 默认格式是列表的列表。

您可以使用列表理解和字符串 join() 添加自己的格式。

col567_fmt = '\n'.join( [ '\t'.join(x) for x in col567.values[0:] ] )
line1=line1[['TYPE', 'NR','','COL1','', 'COL2','', 'COL3', 'COL4', 
         col567_fmt, '', 'REMARK\n', col8.values[0],col8.values[1]]]

另外,如果您想使用to_csv() 进行打印,您需要禁用引用。查看对this question的回复

【讨论】:

  • @ xvan,我得到的行没有排序,并在开头和结尾得到双引号“-3.000 -3.000 0.900 12.751 2.861 1.000 16.500 4.260 1.000 4.750 -0.110 1.000”
  • 已排序的行在 txt 文件中很重要
  • 行以 col567.values[0:] 顺序打印,与您请求的顺序相同。我刚刚在python2上测试过。
  • 添加引号是因为 to_csv() 函数的换行符。检查您是否可以按照我回复的最后一段中的建议删除它们。基本上试试这个: import csv line1.to_csv(table[0]+'.txt',sep='\t',quoting=csv.QUOTE_NONE)
  • 我试过但得到了TypeError: to_csv() got an unexpected keyword argument 'quoting'
猜你喜欢
  • 2011-12-30
  • 2021-05-24
  • 1970-01-01
  • 2012-11-03
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-06
相关资源
最近更新 更多