使用python将数据写入excel

由于经常需要用到这方面的内容,所以要好好记录一下,省的以后老找了

使用的代码版本为 Python3

  1. 首先呢,数据是这个样子的

V04002 V01000 V04001 V10004 V12001 V11002 V13004 V13003 V13011

1 58015 2014 10203 26 19 49 67 0

2 58015 2014 10212 23 21 59 79 282

3 58015 2014 10149 113 20 86 64 87

4 58015 2014 10112 154 14 135 78 615

5 58015 2014 10040 217 17 167 66 530

6 58015 2014 10003 241 12 238 81 571

7 58015 2014 9999 267 14 287 83 1345

8 58015 2014 10033 244 11 271 89 717

第一行对应的含义是:

‘V04002′:’月’,’V01000′:’区站号’,’V04001′:’年’,’V14032′:’日照时数’,’V10202′:’极端最低本站气压’,’V10004′:’平均本站气压’,’V12001′:’平均气温’,’V11002′:’平均风速’,’V10201′:’极端最高本站气压’,’V13004′:’平均水汽压’,’V13003′:’平均相对湿度’,’V13011′:’降水量’,’V12212′:’平均最低气温’

我想用Python把它写入excel中

  1. 用到的知识

(1)使用字典

使用字典将对应的代号转换成中文

(2)读取文件

因为数据是以txt格式来进行保存的,所以需要用到IO操作来读取数据。


with open('read.txt','r') as f:

在这里会用with … as

因为文件对象实现了上下文管理器协议,程序进入with语句块时,会把文件对象赋值给变量f,在程序退出 with 语句块时,会自动调用close方法

需要注意的是,如果是写入文件,可以在函数中指定字符编码格式

with open(‘output.txt’,’w’,encoding=’utf-8′) as f:


with open('output.txt','w',encoding='utf-8') as f:

    contents='愚人之丘'

    f.write(content)

在Python2中可以使用io模块的open。Python2 io.open()等价于Python3 open()

from io import open

(3)pandas

我曾经用pandas爬去过网页上的表格,十分好用,看过介绍,正好在这里也用的上

在dataframe的示例上是这样写的


data = {'Country': ['Belgium', 'India', 'Brazil'],

'Capital': ['Brussels', 'New Delhi', 'Brasília'],

'Population': [11190846,1303171035,207847528]}

df = pd.DataFrame(data,

columns=['Country', 'Capital', 'Population'])

我将数据转换成这种形式,然后使用pandas的to_excel(name,sheet_name=name)将其保存为excel的格式

(4)split(),strip()

split()

通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串


    str.split(str="",num=string.count(str)).

strip()

用于移除字符串头尾指定的字符(默认为空格)。


#!/usr/bin/python

str="0000000this is string example....wow!!!0000000";

printstr.strip('0');

输出即为

this is string example….wow!!!

还可以单独去除一边,也可以使用replace


" xyz ".strip()                    # returns "xyz"

" xyz ".lstrip()                    # returns "xyz "

" xyz ".rstrip()                    # returns " xyz"

" x y z ".replace(' ','')        # returns "xyz"

  1. 代码

# -*- coding: UTF-8 -*-

import pandas as pd



def toexcel(name):

print('*****************************')

print(name)

print('*****************************')

biaotou={'V04002':'月','V01000':'区站号','V04001':'年','V14032':'日照时数','V10202':'极端最低本站气压','V10004':'平均本站气压','V12001':'平均气温','V11002':'平均风速','V10201':'极端最高本站气压','V13004':'平均水汽压','V13003':'平均相对湿度','V13011':'降水量','V12212':'平均最低气温'}

header=[]                                                #存放转换过的表头

data=[]                                                    #存放数据

pre=name.split('.')[0]                              #excel文件名称(小数点前)

xlsname=(pre+'.xlsx')

with open(name) as file:

    for line in file:

        line=line.strip('\n').strip()                #先去掉换行符\n,再去掉前后的空格

        line=line.split(' ')                            #将每行的数据分隔开

        for n in line:

            if n in biaotou.keys():

                header.append(biaotou[n])

            else:

                data.append(line)

                break

df=pd.DataFrame(data,columns=header)

df.to_excel(xlsname,sheet_name=pre)



if __name__ == "__main__":

    name='*****'                #数据名称

    toexcel(name):

  1. 应用到多个文件
    因为数据文件不只是一个是有很多个,要应用到很多个,所以同样要写个方法,获取所有数据的文件的名字,一个个的传给上面的方法,我是通过用到os.listdir() 和os.getcwd() 。

os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。这个列表以字母顺序。 它不包括 ‘.’ 和’..’ 即使它在文件夹中。

os.getcwd() 方法用于返回当前工作目录。

将这两个方法一起用就可以获得当前目录的所有文件的名称(以后会改成传入地址的)

def getname():
  names=[]
  passname=['toexcel.py']              #将不想执行的该程序的文件名,放在这个中,在              
                                                        这里,这个是Python代码的名字
  filenames = os.listdir(os.getcwd())
  for name in filenames:
    if name not in passname:
      names.appends(name)
  return names

将3,4结合,稍加改动就可以将所有数据文件写入到excel中

我知道我的方法比较繁琐,如果有更好的方法,如果那里有什么错误,希望可以告知,共同进步

    原文作者:Sgttt
    原文地址: https://www.jianshu.com/p/e0e5645adf17
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞