Python读写CSV/EXCEL/HTML/SQL/TXT

csv文件是一种以逗号为分隔符的纯文本形式存储的表格数据。

通常csv文件的第一行是列名。

既然是表格类的数据,那么最先想到的应是pandas库的读取方法。pandas以dataframe或series为格式,其实就是表格形式的数据。所以下面介绍用pandas来读取的方法。

当然pandas还可以读取许多其他格式的文件,之后会系统介绍。

pandas读取csv

要使用pandas首先要import pandas库。

然后使用.read_csv()方法,第一个传入的参数的要读取的文件路径,第二个参数传入的是列明的列表。

在下面的例子中,打印出了df的类型,是dataframe格式的。

调用.head()方法可以查看这个表格的前5行数据。如果往.hand(n)传入参数可以指定提取前n行。

import pandas as pd

filename = './files/presidential_polls.csv'
df = pd.read_csv(filename, usecols=['cycle', 'type', 'startdate'])

print type(df)
print df.head()
<class 'pandas.core.frame.DataFrame'>
   cycle        type   startdate
0   2016  polls-plus  10/25/2016
1   2016  polls-plus  10/27/2016
2   2016  polls-plus  10/27/2016
3   2016  polls-plus  10/20/2016
4   2016  polls-plus  10/20/2016

打印这个dataframe我们发现前面怎么有一列0,1,2…的数据,这个是读入数据的时候默认添加的行索引。

series

series是pandas中的另一种数据格式,是一个一维数组的对象。可以看成是dataframe中的其中一列拿出来。

比如取出df中的列名维cycle的一列,那么这一列的格式类型打印出来就死series。

同理,在series中也会默认地带上0开始的行索引

cycle_se = df['cycle']
print type(cycle_se)
print cycle_se.head()
<class 'pandas.core.series.Series'>
0    2016
1    2016
2    2016
3    2016
4    2016
Name: cycle, dtype: int64

pandas写csv

调用.to_csv()方法将数据写入指定的文件中。

写入时可以设置参数index,表示要不要把行索引写进去。

filename = './files/pandas_output.csv'
#df.to_csv(filename)
df.to_csv(filename, index=None)

pandas读写excel文件

excel文件是一般是xls,xlsx的格式。

用pandas读写excel文件的方法与csv完全一致,在此不再详述。

读: 
f = pd.read_excel()

写: 
f.to_excel()


以下对pandas导入文件做了一个归纳,可以导入以下5类数据

1.导入csv

Import pandas ad pd 
Data = pd.read_csv(path)

2.导入excel

Data = pd.read_excel(path)

3.导入mysql

Import pymysql 
Conn = pymysql.connect(host=”主机ip地址”,user=”root”,passwd=”root”.db=”“) 
sql = “select * from table limit 100” 
Data = pd.read_sql(sql,conn)

4.导入html数据,直接读取html中的table数据

Pip install html5lib 
Pip install beatifulsoup4

直接从本地html文件读取表格 
Data = Pd.read_html(“本地网页.html”)

从网页中读取表格 
Data = Pd.read_html(“网址”)

5.导入文本txt

Data = pd.read_table(path)

xt是一种很常见的文件格式。它是由字符串行组成,每行由EOL(end of line)字符隔开:“\n”

要打开文件可以用open(path/filename, access_mode)实现,access_mode有两种模式:一种是“读”,一种是“写”,分别用”r“,”w“表示。

在读取完文件之后,记得一定一定一定要关闭文件:.close()。 
否则会一直保持着与文件的连接,消耗资源。

1. 读操作

1.1 读取全部内容

读取全部内容直接调用.read()即可

运行以下程序,会将指定的文件读入,打印结果与打开txt文件的内容格式是一样的,每一行是一个字符串。

但是,如果直接显示all_content,每行之间就会出现”\r\n”的换行符。

# 一般都会在外部先定义好文件的路径
txt_filename = './files/python_wiki.txt'

# 打开文件
file_obj = open(txt_filename, 'r')

# 读取整个文件内容
all_content = file_obj.read()

# 关闭文件
file_obj.close()

print all_content

all_content
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.[24][25] Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.[26][27] The language provides constructs intended to enable writing clear programs on both a small and large scale.[28]
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.[29]
Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython, the reference implementation of Python, is open source software[30] and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.





'Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.[24][25] Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.[26][27] The language provides constructs intended to enable writing clear programs on both a small and large scale.[28]\r\nPython supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.[29]\r\nPython interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython, the reference implementation of Python, is open source software[30] and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

1.2 逐行读取

有的时候我们会需要先读几行进来看看数据的格式是咋样的,并不需要全部将很大的文件读进来。

使用.readline()方法就可以每次只读一行。

第一次运行的时候会读进第一行,当第二次运行的时候,就会自动读第二行,以此类推。

以下例子中,第一次调用了.readline()并赋值给line1,打印出来是第一行;当第二次运行.readline()并赋值line2,打印出来是第二行内容。

txt_filename = './files/python_wiki.txt'

# 打开文件
file_obj = open(txt_filename, 'r')

# 逐行读取
line1 = file_obj.readline()
print line1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.[24][25] Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.[26][27] The language provides constructs intended to enable writing clear programs on both a small and large scale.[28]
  • 1
  • 2
# 继续读下一行
line2 = file_obj.readline()
print line2

# 关闭文件
file_obj.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.[29]
  • 1
  • 2

如果要逐行打印的话,可以直接设置for循环。

txt_filename = './files/python_wiki.txt'

# 打开文件
file_obj = open(txt_filename, 'r')

for i in range(3):
    print file_obj.readline()

file_obj.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.[24][25] Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.[26][27] The language provides constructs intended to enable writing clear programs on both a small and large scale.[28]

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.[29]

Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython, the reference implementation of Python, is open source software[30] and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

1.3 读取全部内容,返回列表

调用.readlines()可以将文件中的全部内容都读出来,并且返回的格式的“列表”格式

txt_filename = './files/python_wiki.txt'

# 打开文件
file_obj = open(txt_filename, 'r')

lines = file_obj.readlines()

for i, line in enumerate(lines):
    print '%i: %s' %(i, line)

# 关闭文件
file_obj.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
0: Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.[24][25] Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.[26][27] The language provides constructs intended to enable writing clear programs on both a small and large scale.[28]

1: Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.[29]

2: Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython, the reference implementation of Python, is open source software[30] and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

写操作

写操作的模式是”w”

要写入文件的时候调用.write()方法

txt_filename = './files/test_write.txt'

# 打开文件
file_obj = open(txt_filename, 'w')

# 写入全部内容
file_obj.write("《Python数据分析》")
file_obj.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
txt_filename = './files/test_write.txt'

# 打开文件
file_obj = open(txt_filename, 'w')

# 写入字符串列表
lines = ['这是第%i行\n' %i for i in range(100)]
file_obj.writelines(lines)
file_obj.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

with语句

with语句包括了异常处理,自动调用文件关闭操作,非常推荐使用!

每次操作完都要.close关闭以下很麻烦又经常会忘记。所以可以直接用with语句,这样操作完之后就会自动close.

txt_filename = './files/test_write.txt'
with open(txt_filename, 'r') as f_obj:
    print f_obj.read()
  • 1
  • 2
  • 3
  • 4
这是第0行
这是第1行
这是第2行
这是第3行
这是第4行
这是第5行
这是第6行
这是第7行
这是第8行
这是第9行
这是第10行
这是第11行
这是第12行
这是第13行
这是第14行
这是第15行
这是第16行
这是第17行
这是第18行
这是第19行
这是第20行
这是第21行
这是第22行
这是第23行
这是第24行
这是第25行
这是第26行
这是第27行
这是第28行
这是第29行
这是第30行
这是第31行
这是第32行
这是第33行
这是第34行
这是第35行
这是第36行
这是第37行
这是第38行
这是第39行
这是第40行
这是第41行
这是第42行
这是第43行
这是第44行
这是第45行
这是第46行
这是第47行
这是第48行
这是第49行
这是第50行
这是第51行
这是第52行
这是第53行
这是第54行
这是第55行
这是第56行
这是第57行
这是第58行
这是第59行
这是第60行
这是第61行
这是第62行
这是第63行
这是第64行
这是第65行
这是第66行
这是第67行
这是第68行
这是第69行
这是第70行
这是第71行
这是第72行
这是第73行
这是第74行
这是第75行
这是第76行
这是第77行
这是第78行
这是第79行
这是第80行
这是第81行
这是第82行
这是第83行
这是第84行
这是第85行
这是第86行
这是第87行
这是第88行
这是第89行
这是第90行
这是第91行
这是第92行
这是第93行
这是第94行
这是第95行
这是第96行
这是第97行
这是第98行
这是第99行

猜你喜欢

转载自blog.csdn.net/qq_35654080/article/details/82501486
今日推荐