python遍历文件内容|用python读取文本文件对读出的每一行进行操作这个怎么写

python遍历文件内容|用python读取文本文件对读出的每一行进行操作这个怎么写的第1张示图

Ⅰ python:遍历文件并搜索/读取

os.walk()

Ⅱ Python中如何遍历指定目录下的所有文件

例如:在C:\TDDOWNLOAD目录下有a.txt、b.txt两个文件,另有\sub1子文件夹,C:\TDDOWNLOAD\sub1下又有c.txt、d.txt两个文件。 1. os.walkos.walk()返回一个三元素的tuple:当前路径、子文件夹名称、文件列表。>>> import os>>> def fun( path ):… for root, dirs, files in os.walk( path ):… for fn in files:… print root, fn… >>> fun( r'C:\TDDOWNLOAD' )C:\TDDOWNLOAD a.txtC:\TDDOWNLOAD b.txtC:\TDDOWNLOAD\sub1 c.txtC:\TDDOWNLOAD\sub1 d.txt>>> 2. glob.globglob.glob()只接受一个参数,这个参数既代有路径,又代有匹配模式,返回值为一个列表。注意,glob.glob()无法直接穿透子文件夹,需要自己处理:>>> def fun( path ):… for fn in glob.glob( path + os.sep + '*' ): # '*'代表匹配所有文件… if os.path.isdir( fn ): # 如果结果为文件夹… fun( fn ) # 递归… else:… print fn… >>> fun( r'C:\TDDOWNLOAD' )C:\TDDOWNLOAD\a.txtC:\TDDOWNLOAD\b.txtC:\TDDOWNLOAD\sub1\c.txtC:\TDDOWNLOAD\sub1\d.txt>>> '*'为匹配模式,代表匹配所有文件,只有这样才能将子文件夹查出来,以便递归深入,探查下一层的文件。

Ⅲ python读取文本内每行指定内容

可以参考下面的代码:

f=file(yourpath)

for line in f:

t = line.split("==")

part_1 = t[0] + "=="

(part_2,part_3) = t[1].split("–")

del t

print "第一段:%s第二段:%s第三段:%s" %(part_1,part_2,part_3)

(3)python遍历文件内容扩展阅读:

python参考函数

callable(obj) 查看一个obj是不是可以像函数一内样调用容

repr(obj) 得到obj的表示字符串,可以利用这个字符串eval重建该对象的一个拷贝

eval_r(str) 表示合法的python表达式,返回这个表达式

hasattr(obj,name) 查看一个obj的name space中是否有name

setattr(obj,name,value) 为一个obj的name space中的一个name指向vale这个object

Ⅳ 如何用Python os.path.walk方法遍历搜索文件内容的操作详解

本文是关于如何用Python os.path.walk方法遍历搜索文件目录内容的操作详解的文章,python 代码中用os.path.walk函数这个python模块的方法来遍历文件,python列出文件夹下的所有文件并找到自己想要的内容。文中使用到了Python os模块和Python sys模块,这两个模块具体的使用方法请参考玩蛇网相关文章阅读。Python os.path.walk方法遍历文件搜索内容方法代码如下:?041import os, sys#代码中需要用到的方法模块导入 listonly = False skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb'] # ignore binary files def visitfile(fname, searchKey): global fcount, vcount try: if not listonly: if os.path.splitext(fname)[1] in skipexts: pass elif open(fname).read().find(searchKey) != -1: print'%s has %s' % (fname, searchKey) fcount += 1 except: pass vcount += 1 #www.iplaypy.com def visitor(args, directoryName,filesInDirectory): for fname in filesInDirectory: fpath = os.path.join(directoryName, fname) if not os.path.isdir(fpath): visitfile(fpath,args) def searcher(startdir, searchkey): global fcount, vcount fcount = vcount = 0 os.path.walk(startdir, visitor, searchkey) if __name__ == '__main__': root=raw_input("type root directory:") key=raw_input("type key:") searcher(root,key) print 'Found in %d files, visited %d' % (fcount, vcount)

Ⅳ python如何读取文件的内容

# _*_ coding: utf-8 _*_

import pandas as pd

# 获取文件的内容

def get_contends(path):

with open(path) as file_object:

contends = file_object.read()

return contends

# 将一行内容变成数组

def get_contends_arr(contends):

contends_arr_new = []

contends_arr = str(contends).split(']')

for i in range(len(contends_arr)):

if (contends_arr[i].__contains__('[')):

index = contends_arr[i].rfind('[')

temp_str = contends_arr[i][index + 1:]

if temp_str.__contains__('"'):

contends_arr_new.append(temp_str.replace('"', ''))

# print(index)

# print(contends_arr[i])

return contends_arr_new

if __name__ == '__main__':

path = 'event.txt'

contends = get_contends(path)

contends_arr = get_contends_arr(contends)

contents = []

for content in contends_arr:

contents.append(content.split(','))

df = pd.DataFrame(contents, columns=['shelf_code', 'robotid', 'event', 'time'])

(5)python遍历文件内容扩展阅读:

python控制语句

1、if语句,当条件成立时运行语句块。经常与else, elif(相当于else if) 配合使用。

2、for语句,遍历列表、字符串、字典、集合等迭代器,依次处理迭代器中的每个元素。

3、while语句,当条件为真时,循环运行语句块。

4、try语句,与except,finally配合使用处理在程序运行中出现的异常情况。

5、class语句,用于定义类型。

6、def语句,用于定义函数和类型的方法。

Ⅵ 请教大神,python遍历目录,根据目录下获取的文件信息,到其他目录查找,并记录到列表

os包的listdir函数可以列出一个文件夹下的所有文件名,返回的是一个列表

importosfilenames=os.listdir('g:\')

可以通专过os.path.isfile()函数判断一个文件是否存属在

os.path.isfile('g:meelo.txt')

Ⅶ 用python读取文本文件,对读出的每一行进行操作,这个怎么写

用python读取文本文件,对读出的每一行进行操作,写法如下:

f=open("test.txt","r")

whileTrue:

line=f.readline()

ifline:

pass#dosomethinghere

line=line.strip()

p=line.rfind('.')

filename=line[0:p]

print"create%s"%line

else:

break

f.close()

Ⅷ python 如何遍历文件夹里所有的txt文件

PY不会,其它语言我会

Ⅸ python遍历文本并删除特定内容

按 指定行数 分页读取好处理:

defiterpage(istream,pagesize):buffer=[]fordatainistream:buffer.append(data)iflen(buffer)>=pagesize:yieldbufferbuffer=[]ifbuffer:yieldbufferwithopen("source.txt",'rt')ashandle:forpageiniterpage(handle,1000):printpage#oryourbusinesslogicalprint"-"*32#pagebreak

删除文本文件的前N行:

defremovehead(filename,headlines):buffer=[]withopen(filename,'rt')ashandle:fori,lninenumerate(handle):ifln<headlines:continuebuffer.append(ln)withopen(filename,'wt')ashandle:handle.writelines(buffer)

或者:

defgetandremovehead(filename,headlines):withopen(filename,'rt')ashandle:buffer=handle.readlines()withopen(filename,'wt')ashandle:handle.writelines(buffer[headlines:])returnbuffer[:headlines]

但遇到大文本文件时,删除其中N行不是很理想的业务方案

Ⅹ 怎样用Python遍历一个目录下所有文件

importospath='C:/'forroot,dirs,filesinos.walk(path):print("Root=",root,"dirs=",dirs,"files=",files)#效果嘛复..你电制脑上运行下就知道了

未经允许不得转载:山九号 » python遍历文件内容|用python读取文本文件对读出的每一行进行操作这个怎么写

赞 (0)