python读取文件存入列表(python读取文件rb)
python文件读取与写入
open(filepath) :打开文件
open(filepath,'r') :打开方式,默认是读取
open(filepath).read() :读取文件中的内容
open(filepath).readline() :读取文件中一行的内容
open(filepath).readline()[1] :读取文件中的内容,返回值是列表。
open(filepath).close() :关闭文件
open(filepath).seek(0) :将光标回到首位
with open()函数,不用close()方法,默认自动关闭,所以需要制定一些规则.
文件内建函数和方法:
open() : 打开文件
read() :输入
readline() :输入一行
seek() :文件内移动
write() :输出
close() :关闭文件
python 读取文件转换为列表
python 读取文本文件内容转化为python的list列表,案例如下:
1、目的
读取cal.txt内容,然后通过python脚本转化为list内容
2、文件内容
cal.txt
12
13
14
15
16
3、Python编写cal.py脚本内容
#!/usr/bin/python
#coding?=?UFT-8
result=[]
fd?=?file(?"cal.txt",?"r"?)
for?line?in?fd.readlines():
????result.append(list(map(int,line.split(','))))
print(result)
for?item?in?result:
????for?it?in?item:
???????print?it
4、执行转换为List列表结果内容:
[[12],?[13],?[14],?[15],?[16]]
12
13
14
15
16

python怎么将读出来的文件放到列表
csv文件的读取:
前期工作:在定义的py文件里边创建一个excel文件,并另存为csv文件,放入三行数据,我这里是姓名+年龄(可以自己随意写)
首先我们要在python环境里导入csv板块(测试小白的我喜欢用pycharm)
然后我们定义一个csv文件的变量csv_file,然后通过open对此文件进行打开,打开模式采用‘r’(read:读模式),这里不懂的各位小白白可以百度下文件的访问模式
如下图所示:
图中打印出来的csv_file只是一个对象的模型(如图中的1),我们需要对这个模型进行遍历打印,通过打印我们可以清晰的看到我们打印的数据
csv文件的写入:
通过上面我们可以对csv的文件进行了读取,各位小白们有没有感觉很简单呢(我当时乐开花了),下面我们就讲一下csv的读取
在开始前我们要定义两组数据,进行下面的写入
stu1 = ['marry',26]
stu2 = ['bob',23]
1.写入的第一步同样也是打开文件,因为我们是要写入,所以我们用的模式就是 ?'a' ?模式,追加内容,至于"newline="就是说因为我们的csv文件的类型,如果不加这个东西,当我们写入东西的时候,就会出现空行,这个大家可以尝试着不加试试一下,也可以"老乌龟的屁股"(规定)
out = open('Stu_csv.csv','a', newline='')
2.下面我们定义一个变量进行写入,将刚才的文件变量传进来,dialect就是定义一下文件的类型,我们定义为excel类型
csv_write = csv.writer(out,dialect='excel')
3.然后进行数据的写入啦,啦啦啦,终于要结束了,写入的方法是writerow,通过写入模式对象,调用方法进行写入
csv_write.writerow(stu1)
csv_write.writerow(stu2)
4.最后各位小白可以用你们最熟悉的一句语法进行漂亮的收尾,66666
print ("write over")
具体的代码如下:
import csv
#csv 写入
stu1 = ['marry',26]
stu2 = ['bob',23]
#打开文件,追加a
out = open('Stu_csv.csv','a', newline='')
#设定写入模式
csv_write = csv.writer(out,dialect='excel')
#写入具体内容
csv_write.writerow(stu1)
csv_write.writerow(stu2)
print ("write over")
执行结果:
啦啦啦,开不开心,刺不刺激,纯小白内容,谢谢大家的阅读,欢迎留言交流,不要忘记我,我就是宇宙无敌的python小白白!
python读取excel文件,将每一行都保存为一个列表。每一行对应一个列表。
python读写excel文件要用到两个库:xlrd和xlwt,首先下载安装这两个库。
1、#读取Excel
import?xlrd
data = xlrd.open_workbook(excelFile)
table = data.sheets()[0]
nrows = table.nrows #行数
ncols = table.ncols #列数
for i in xrange(0,nrows):
rowValues= table.row_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 = xlwt.easyxf('font: bold 1')
#style = xlwt.easyxf('font: bold 0, color red;')#红色字体
#style2 = xlwt.easyxf('pattern: pattern solid, fore_colour yellow; font: bold on;') # 设置Excel单元格的背景色为黄色,字体为粗体
for?svalue in?rowValueList:
strValue = unicode(str(svalue),'utf-8')
if?isBold:
sheet.write(rowIndex,i,strValue,style)
else:
sheet.write(rowIndex,i,strValue)
i = i + 1
'''写excel文件'''
def?save_Excel(strFile):
excelFile = unicode(strFile,?"utf8")
wbk = xlwt.Workbook()
sheet = wbk.add_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):
valueList.append(j*i)
WriteSheetRow(sheet,valueList,rowIndex,False)
wbk.save(excelFile)
style2 = xlwt.easyxf('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'随着Django1.4第二个候选版的发布,虽然还不支持Python3,但Django团队已经在着手计划中,据官方博客所说,Django1.5将会试验性的支持python3'}
]# 定义excel操作句柄excle_Workbook = Workbook()
excel_sheet_name = time.strftime('%Y-%m-%d')
excel_sheet = excle_Workbook.add_sheet(excel_sheet_name)
index = 0#标题for data in excel_headDatas:
excel_sheet.write(0, index, data)
index += 1index = 1#内容for article in articles:
colIndex = 0 ? ?for item in excel_headDatas:
excel_sheet.write(index, colIndex, article[item])
colIndex += 1
index += 1#保存test.xlsx到当前程序目录excle_Workbook.save('test.xlsx')# db = mongoDB.mongoDbBase()# db.Get_information_stat()
python 读取txt文件到列表中
#-*-?coding:utf-8?-*-
f?=?open('123.txt',?'r')??????????????#文件为123.txt
sourceInLines?=?f.readlines()??#按行读出文件内容
f.close()
new?=?[]???????????????????????????????????#定义一个空列表,用来存储结果
for?line?in?sourceInLines:
????temp1?=?line.strip('\n')???????#去掉每行最后的换行符'\n'
????temp2?=?temp1.split(',')?????#以','为标志,将每行分割成列表
????new.append(temp2)??????????#将上一步得到的列表添加到new中
????
print?new
最后输出结果是:[['aaa',?'bbb',?'ccc'],?['ddd',?'eee',?'fff']],注意列表里存的是字符串'aaa',不是变量名aaa。
用python+将文件中的内容存储为字符串列表?
可以使用以下代码将文件中的内容存储为字符串列表:
pythonwith open('filename.txt', 'r') as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
这里使用了`with`语句来打开文件,这样可以确保文件在使用完后自动关闭。
`readlines()`方法将文件中的每一行读取为一个字符串,并将它们存储在一个列表中。`strip()`方法用于去除每行字符串末尾的换行符。最后,使用列表推导式将每行字符串存储为一个新的列表`lines`。