数据有多行,用python进行文件读取,并将文件所有行的前21个数据保存到一个二维列表中,最后一个

数据有多行,用python进行文件读取,并将文件所有行的前21个数据保存到一个二维列表中,最后一个,第1张

data=[]

for i in range(文件数):

    dataappend([])

    data[i]append(前21行个数据为一个列表)

    

效果:data=[[前21行],[前21行],前21行],[前21行]]

python3 环境

任何语言想读取一个文件的多列基本都需要从头遍历一遍,直到读取到指定列。python中提供readlines函数,返回一个list对象,对象内容为一列。推荐使用该函数。

举例: 读取第1,5,19列数据,读取后推出程序。

f = open("filetxt","r")

i=0

for line in freadlines():

    if i in [1,5,19]:

        print line

    i+=1

    if i > 19: break

fclose()

11 读取整个文件

要读取文件,需要一个包含几行文本的文件(文件PI_DESCtxt与file_readerpy在同一目录下)

PI_DESCtxt

31415926535

8979323846

2643383279

5028841971

file_readerpy

with open("PI_DESCtxt") as file_object:

contents = file_objectread()

print(contents)

我们可以看出,读取文件时,并没有使用colse()方法,那么未妥善的关闭文件,会不会导致文件收到损坏呢?在这里是不会的,因为我们在open()方法前边引入了关键字with,该关键字的作用是:在不需要访问文件后将其关闭

12文件路径

程序在读取文本文件的时候,如果不给定路径,那么它会先在当前目录下进行检索,有时候我们需要读取其他文件夹中的路径,例如:

现在文件PI_DESCtxt存储在python目录的子文件夹txt中

那么我们读取文本内容的代码得修改为:

with open("txt\PI_DESCtxt") as file_object:

contents = file_objectread()

print(contents)

给open参数传递的参数得给相对路径

在Windows中,使用反斜杠(\),但是由于python中,反斜杠被视为转义字符,在Windows最好在路径开头的单(双)引号前加上r

相对路径:即相对于程序文件的路径

绝对路径:即文本在硬盘上存储的路径

使用绝对路径的程序怎么写呢 ?

with open(r"D:\python\txt\PI_DESCtxt") as file_object:

contents = file_objectread()

print(contents)

13逐行读取

读取文件时,可能需要读取文件中的每一行,要以每一行的方式来检查文件或者修改文件,那么可以对文件对象使用for循环

file_path = 'txt\PI_DESCtxt'with open(file_path) as file_object:

for line in file_object:

print(line)

程序运行结果如下:

通过运行结果我们可以看出,打印结果中间有很多空白行,这些空白行是怎么来的呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加一个换行符,因此每行末尾就有2个换行符:一个来自文件,另外一个来自print,消除这些换行符,只需要使用方法rstrip()

file_path = 'txt\PI_DESCtxt'with open(file_path) as file_object:

for line in file_object:

print(linerstrip())

打印结果

通过运行结果我们可以看出,打印结果中间有很多空白行,这些空白行是怎么来的呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加一个换行符,因此每行末尾就有2个换行符:一个来自文件,另外一个来自print,消除这些换行符,只需要使用方法rstrip()

file_path = 'txt\PI_DESCtxt'with open(file_path) as file_object:

for line in file_object:

print(linerstrip())

打印结果

14创建一个包含文件各行内容的列表

使用关键字with时,open()返回的文件对象只能在with代码块可用,如果要在with代码块外访问文件的内容,可在with块中将文件各行存储在一个列表,并在with代码块外使用该列表

file_path = 'txt\PI_DESCtxt'with open(file_path) as file_object:

lines = file_objectreadlines()for line in lines:

print(linerstrip())

15使用文件的内容

在上面一节中我们提到把数据提取到内存中,那么我们就可以对数据进行随心所欲的 *** 作了

需要:将圆周率连在一起打印出来(删除空格),并打印其长度

file_path = 'txt\PI_DESCtxt'with open(file_path) as file_object:

lines = file_objectreadlines()pi_str = ''for line in lines:

pi_str += linestrip()print(pi_strrstrip())print(len(pi_strrstrip()))

file_path = 'txt\PI_DESCtxt'with open(file_path) as file_object:

lines = file_objectreadlines()pi_str = ''for line in lines:

pi_str += linestrip()print(pi_strrstrip())print(len(pi_strrstrip()))

注意最后print语句并没有缩进,如果是缩进的话就会每取一行打印一次

打印效果如下

python读写excel文件要用到两个库:xlrd和xlwt,首先下载安装这两个库。

1、#读取Excel

import xlrd

data = xlrdopen_workbook(excelFile)

table = datasheets()[0]

nrows = tablenrows #行数

ncols = tablencols #列数

for i in xrange(0,nrows):

rowValues= tablerow_values(i) #某一行数据

for item in rowValues:

print item

2、写Excel文件

'''往EXCEl单元格写内容,每次写一行sheet:页签名称;row:行内容列表;rowIndex:行索引;

isBold:true:粗字段,false:普通字体'''

def WriteSheetRow(sheet,rowValueList,rowIndex,isBold):

i = 0

style = xlwteasyxf('font: bold 1')

#style = xlwteasyxf('font: bold 0, color red;')#红色字体

#style2 = xlwteasyxf('pattern: pattern solid, fore_colour yellow; font: bold on;') # 设置Excel单元格的背景色为**,字体为粗体

for svalue in rowValueList:

strValue = unicode(str(svalue),'utf-8')

if isBold:

sheetwrite(rowIndex,i,strValue,style)

else:

sheetwrite(rowIndex,i,strValue)

i = i + 1

'''写excel文件'''

def save_Excel(strFile):

excelFile = unicode(strFile, "utf8")

wbk = xlwtWorkbook()

sheet = wbkadd_sheet('sheet1',cell_overwrite_ok=True)

headList = ['标题1','标题2','标题3','标题4','总计']

rowIndex = 0

WriteSheetRow(sheet,headList,rowIndex,True)

for i in xrange(1,11):

rowIndex = rowIndex + 1

valueList = []

for j in xrange(1,5):

valueListappend(ji)

WriteSheetRow(sheet,valueList,rowIndex,False)

wbksave(excelFile)

style2 = xlwteasyxf('pattern: pattern solid, fore_colour yellow; font: bold on;')

在设置上Excel单元格的背景色时,fore_colour 支持的颜色是有限的,仅支持一下颜色

aqua 0x31

black 0x08

blue 0x0C

blue_gray 0x36

bright_green 0x0B

brown 0x3C

coral 0x1D

cyan_ega 0x0F

dark_blue 0x12

dark_blue_ega 0x12

dark_green 0x3A

dark_green_ega 0x11

dark_purple 0x1C

dark_red 0x10

dark_red_ega 0x10

dark_teal 0x38

dark_yellow 0x13

gold 0x33

gray_ega 0x17

gray25 0x16

gray40 0x37

gray50 0x17

gray80 0x3F

green 0x11

ice_blue 0x1F

indigo 0x3E

ivory 0x1A

lavender 0x2E

light_blue 0x30

light_green 0x2A

light_orange 0x34

light_turquoise 0x29

light_yellow 0x2B

lime 0x32

magenta_ega 0x0E

ocean_blue 0x1E

olive_ega 0x13

olive_green 0x3B

orange 0x35

pale_blue 0x2C

periwinkle 0x18

pink 0x0E

plum 0x3D

purple_ega 0x14

red 0x0A

rose 0x2D

sea_green 0x39

silver_ega 0x16

sky_blue 0x28

tan 0x2F

teal 0x15

teal_ega 0x15

turquoise 0x0F

violet 0x14

white 0x09

yellow 0x0D"""

另外一种方式是 用pyExcelerator

from pyExcelerator import # excel 第一行数据excel_headDatas = [u'发布时间', u'文章标题', u'文章链接', u'文章简介']

articles =[

{u'发布时间':u'2017年5月9日',

u'文章标题':u'Python项目实战教程:国内就能访问的google搜索引擎',

u'

u'文章简介':u'大家可以留言、想了解python那个方向的知识、不然我也不知道'},

{u'发布时间':u'2017年5月4日',

u'文章标题':u'对于学习Django的建议、你知道的有那些',

u'文章链接':',

u'文章简介':u'随着Django14第二个候选版的发布,虽然还不支持Python3,但Django团队已经在着手计划中,据官方博客所说,Django15将会试验性的支持python3'}

]# 定义excel *** 作句柄excle_Workbook = Workbook()

excel_sheet_name = timestrftime('%Y-%m-%d')

excel_sheet = excle_Workbookadd_sheet(excel_sheet_name)

index = 0#标题for data in excel_headDatas:

excel_sheetwrite(0, index, data)

index += 1index = 1#内容for article in articles:

colIndex = 0    for item in excel_headDatas:

excel_sheetwrite(index, colIndex, article[item])

colIndex += 1

index += 1#保存testxlsx到当前程序目录excle_Workbooksave('testxlsx')# db = mongoDBmongoDbBase()# dbGet_information_stat()

def loadDataSet(filename):

    dataMat=[]

    fr=open(filename)

    for line in frreadlines():

        line = linereplace('"','')

        curLine=linestrip()split('\t')

        aa = [float(i) for i in curLine]

        dataMatappend(aa)

    return dataMat

dataMat=loadDataSet('testtxt')

print (dataMat)

python读取文件内容的方法:

一最方便的方法是一次性读取文件中的所有内容并放置到一个大字符串中:

all_the_text = open('thefiletxt')read( )

# 文本文件中的所有文本

all_the_data = open('abinfile','rb')read( )

# 二进制文件中的所有数据

为了安全起见,最好还是给打开的文件对象指定一个名字,这样在完成 *** 作之后可以迅速关闭文件,防止一些无用的文件对象占用内存。举个例子,对文本文件读取:

file_object = open('thefiletxt')

try:

all_the_text = file_objectread( )

finally:

file_objectclose( )

不一定要在这里用Try/finally语句,但是用了效果更好,因为它可以保证文件对象被关闭,即使在读取中发生了严重错误。

二最简单、最快,也最具Python风格的方法是逐行读取文本文件内容,并将读取的数据放置到一个字符串列表中:

list_of_all_the_lines = file_objectreadlines( )

这样读出的每行文本末尾都带有"\n"符号;如果你不想这样,还有另一个替代的办法,比如:

list_of_all_the_lines = file_objectread( )splitlines( )

list_of_all_the_lines = file_objectread( )split('\n')

list_of_all_the_lines = [Lrstrip('\n') for L in file_object]

最简单最快的逐行处理文本文件的方法是,用一个简单的for循环语句:

for line in file_object:

process line

这种方法同样会在每行末尾留下"\n"符号;可以在for循环的主体部分加一句:

lineline = linerstrip('\n')

或者,你想去除每行的末尾的空白符(不只是'\n'\),常见的办法是:

lineline = linerstrip( )

以上就是关于数据有多行,用python进行文件读取,并将文件所有行的前21个数据保存到一个二维列表中,最后一个全部的内容,包括:数据有多行,用python进行文件读取,并将文件所有行的前21个数据保存到一个二维列表中,最后一个、我想用Python读取txt文件中的多列怎么做呀我是初学者、Python如何从文件读取数据等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/9297493.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-26
下一篇 2023-04-26

发表评论

登录后才能评论

评论列表(0条)

保存