① python怎么读取指定目录、指定文件、指定行的值呢 麻烦回答的时候举个例子
对于文件,python通常是无法读取指定行的。不过是可以进行"曲线救国",但是这仅对文本文件生效,对于
二进制文件
,本身是没有行的概念的,讨论也没意义,下面是一种可能的解决方案。
path='c:\\
documents
'
filename='readme.txt'
fullfilename='%s\\%s'%(path,filename)
def getContentByRowNumber(rownumber,filehandle):
oldfilePos=filehandle.tell()
i=0
filehandle.seek(0)
while i
追问:
可以加一下注释?因为个人知识有限,有些实在看不懂
评论
0
3
加载更多
② 怎么用python读取txt文件里指定行的内容,并导入excel
举个简单的例子,我这里有一个txt文件,文件中每一个row包含的是用户名和用户的身高,我们这里需要获取特定的行内容,比如身高大于170cm的内容,写入excel中。
data.txt
张三172cm
李四183cm
王五166cm
赵六159cm
孙乐乐185cm
周熊熊169cm
苏鹏鹏176cm
吴刚刚191cm
韩轩轩172cm
sheet.py
'''
获取文件信息
'''
fi=open("data.txt")
lines=fi.readlines()
#读取身高大于170cm
data=[]
forhumaninlines:
hinfo=human.split()
ifhinfo:
ifint(hinfo[1][:3])>=170:
data.append(tuple(hinfo))
'''
写入excel
'''
importxlwt
#创建workbook和sheet对象
workbook=xlwt.Workbook()#Workbook的开头W大写
sheet1=workbook.add_sheet('sheet1',cell_overwrite_ok=True)
#向sheet页中写入数据
sheet1.write(0,0,'姓名')
sheet1.write(0,1,'身高cm')
row=1
foriindata:
sheet1.write(row,0,i[0])#i0姓名
sheet1.write(row,1,i[1])#i1身高
row+=1
workbook.save('c.xlsx')#写入excel
执行sheet.py 后,打开同级目录下的c.xlsx
③ 怎么用python读取txt中的特定行
举个例子:
numpy = []
with open("linshi.txt", "r") as f:
data = f.readlines()
a = [1, 3, 5, 7, 9]
for i in a:
x = data[i-1]
numpy.append(x)
print(numpy)
④ 怎么用python读取txt文件里指定行的内容,并导入excel
全文使用的是xlswriter模块写的,也有人使用xlrd与xlutils模块实现,不过还未进行验证
import xlsxwriter
workbook = xlsxwriter.Workbook("D:\Program Files\subpy\sql2.xlsx")#在指定目录下创建一个excle
worksheet = workbook.add_worksheet("students")#新建一个sheet
title_index = ["A","B","C","D"]#sheet中的区域
li = [] #定义一个空列表
blod = workbook.add_format({"bold":True})#定义exlce中写入的字体with open("D:\Program Files\subpy\tets.txt",'r') as f1:#打开txt文档
lines = f1.readlines()#读取所有行内容
n = -1#定义一个变量
for x in lines:#逐行读取
n=n+1
li.append(x[:-1])#去掉回车符
y= x.split#以空格分字符
for i in range(len(title_index)):#读取excle区域下标
# for i,j in enumerate(title_index):
content = y[i]#单个字符读取
worksheet.write(n,i,content,blod)#分行分列写入workbook.
close#关闭excle
⑤ python读取文本内每行指定内容
如果每个数字的位数是固定的,那就是这样:
file = open ("c:\myfile.txt") #填入完整文件路径+文件名
lines=file.readlines()
for line in lines:
a=int(line[3:9])
b=int(line[11:14])
c=int(line[16:19])
print a,b,c
⑥ 如何用python读取文本中指定行的内容
txt文件可以用行号,用readlines读取出来的数据是一个列表,你可以使用:
f = open('', 'r')
line = f.readlines()
line_need = line[行号-1]
这样来取指定行
⑦ python如何指定写入内容的行数,以及如何读取指定行数(已知)
不用关心行数。
只要把要保存的变量,用字典组织起来。然后用str()行数转成字符串存到文件中。
读取的时候,只要将读取的字符串,用eval()行数,再转回字典,然后按key进行区分,分别还给变量就可以了。
⑧ python读取csv文件的某一行
1.全部读到成列表然后选取行(容易超时,乱码等问题)
2.利用迭代工具,代码如下:
from itertools import islice
with open('data.tsv', 'r') as f:
for line in islice(f, 1, None):
# process data
f.close()
修改islice函数中第2个参数n即可,表示读到f文件对象的第n行
⑨ python怎么提取文件的某一行
total=你要提取的行的行号
IStream=open("文件名",'r')
args=IStream.readlines()
line=args[total-1]#你所要的文件的某一行
⑩ Python 读取指定行数
F=('n'.join(open('C:\Users\Administrator\Desktop\ID.txt','r',encoding='gbk').readlines()[b:c]))