尝试将值从datfiles导出到CSV

时间:2018-09-28 09:26:58

标签: python csv export

我正在尝试在csv文件上导出一些值。我运行以下代码:

import glob
import csv

lines=[]

files = glob.glob('*#*')             
for file in files:
    with open(file,'r+') as f:
        first_line = f.readline()
        lines.append(first_line[28:39])

print(lines)

我发现要导出到csv的就绪代码。当然不是完全正确的。我不需要我认为的循环(用于val ..)

with open("test.csv", "r+") as output:
    writer = csv.writer(output, lineterminator='\n')
         for val in lines:
    writer.writerow([lines])     

我面临的问题是由于我将值存储在列表中。因此它们在csv中的输出有点混乱。有什么方法可以将它们导出到excel的第二列中,并在第一列中添加文件名?

我的文件具有类似(0116,0216,0316等)的名称

我知道使用熊猫会很有用,因为我正在处理数据文件和Excel。但是我不熟悉pandas atm,因此另一种方法也可能有用。

我正在添加两个可能有帮助的屏幕截图

the files that I read have the below input and i retrieve the first row and the second column number in our example the value "1660195"

the files are general files with just txt input

所以我想在导出的csv的第二列中导出“ 1660195”。在第一列中,我想要文件的名称。例如

[屏幕截图1输入]

[屏幕快照2个文件]

the output csv should be like that

2 个答案:

答案 0 :(得分:0)

你好,我实际上尝试过熊猫,输出正常。

import glob


import pandas as pd

lines=[]

files = glob.glob('*#*')             
for file in files:
    with open(file,'r+') as f:
        first_line = f.readline()
        lines.append(first_line[28:39])



df = pd.DataFrame(lines)
df.to_csv('tst.csv')

答案 1 :(得分:0)

您可以直接从datafle在pandas中创建数据框,然后尝试类似的操作。

>>> df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
>>> df
  foo
0   A
2   B
1   C
>>> df.loc[df.index[0], 'foo']  # here index[0] is your first row & column is 'foo'
'A'

>>> df.loc[df.index[1], 'foo']
'B'

OR

>>> df.iloc[0]
foo    A
Name: 0, dtype: object

另一个例子:

                              Region                            Nation        Item Type  Order Date   Order ID   Ship Date  Units Sold  U_Price  Total Cost
0               Australia and Oceania                            Tuvalu        Baby Food   5/28/2010  669165933   6/27/2010        9925   255.28  1582243.50
1   Central America and the Caribbean                           Grenada           Cereal   8/22/2012  963881480   9/15/2012        2804   205.70   328376.44
2                              Europe                            Russia  Office Supplies    5/2/2014  341417157    5/8/2014        1779   651.21   933903.84
3                  Sub-Saharan Africa             Sao Tome and Principe           Fruits   6/20/2014  514321792    7/5/2014        8102     9.33    56065.84
4                  Sub-Saharan Africa                            Rwanda  Office Supplies    2/1/2013  115456712    2/6/2013        5062   651.21  2657347.52

所以您可以像下面这样编码。

import pandas as pd
##################### Pandas Display Settings For Terminal #########
pd.set_option('display.height', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('expand_frame_repr', True)
##################### END OF THE Display Settings ###################

df_csv = pd.read_csv("Sales-Records.csv")).fillna('')
df_trim = df_csv[['Region', 'Nation', 'Item Type','Order Date', 'Order ID','Ship Date', 'Units Sold', 'U_Price','Total Cost']]
print(df_trim.loc[df_trim.index[0], 'Nation'])

输出

./test.py
Tuvalu