python怎么读取文件夹里部分的文件(python读取文件部分内容)
python怎么读取文件夹内容
#encoding:utf-8
import os
#设置文件夹所在路径,我这里设置哦当前路径
path = './'
#列出路径下所有的一级目录+文件
files = os.listdir(path)
print files
#利用递归,列出目录下包括子目录所有的文件及文件夹(但是没有分级,如果需要分级,自己写吧)
files1 = []
def listfiles(path):
for i in os.listdir(path):
if os.path.isdir(path+i):
files1.append(i)
listfiles(path+i)
else:
files1.append(i)
listfiles(path)
print files1
python中怎么读取文件内容
用open命令打开你要读取的文件,返回一个文件对象
然后在这个对象上执行read,readlines,readline等命令读取文件
或使用for循环自动按行读取文件
python 怎么读取当前目录下指定文件
读文本文件
input = open('data', 'r')
#第二个参数默认为r
input = open('data')
读二进制文件
input = open('data', 'rb')
读取所有内容
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
读固定字节
file_object = open('abinfile', 'rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close( )
读每行
list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,还可以直接遍历文件对象获取每行:
for line in file_object:
process line
python 随机读取文件夹内一个文本文件
来个批量读取文件的例子:
def?read_test_data():
????for?parent,dirnames,filenames?in?os.walk(pbx_test_path):
????????for?filename?in?filenames:
????????????if?filename[:5]?==?"TEST_":
????????????????file_path?=?pbx_test_path+"\%s"?%?filename
????????????????#file_bak_path?=?pbx_test_path_bak+"\%s"?%?filename
????????????????if?os.path.isfile(file_path):
????????????????????#print?file_path
????????????????????read_by_file(file_path)
????????????????????#shutil.copyfile(file_path,file_bak_path)
????????????????????try:
????????????????????????os.remove(file_path)
????????????????????except??WindowsError:
????????????????????????pass
?????????????????
def?read_by_file(file_path):
????file_object?=?open(file_path)
????count?=?0
????thefile?=?open(file_path,?'rb')
????while?True:
????????buffer?=?str(thefile.readline())
????????if?not?buffer:
????????????break
????????all_test_list?=?buffer.split(";")
????????all_test_list?=?all_test_list[:len(all_test_list)-1]#去除回车行
????????ziduan_str?=?""
????????value_str?=?""
????????for?i,test?in?enumerate(all_test_list):
????????????test_attr_list?=?test.split("=")
????????????ziduan_str?+=?""+test_attr_list[0]+","
????????????value_str?+=?"'"+test_attr_list[1]+"',"
????????ziduan_str?=?"("+ziduan_str[:len(ziduan_str)-1]+")"
????????value_str?=?"("+value_str[:len(value_str)-1]+")"
????????sql_str?=?"insert?into?pbx_test"+ziduan_str+"?values"+value_str+""
????????#mssql.insert(sql_str)
????????session.execute(sql_str)
????????count?+=?buffer.count('\n')
????commit()
????thefile.close()
python怎么提取出文件里的指定内容
python读取文件内容的方法:
一.最方便的方法是一次性读取文件中的所有内容并放置到一个大字符串中:
all_the_text = open('thefile.txt').read( )
# 文本文件中的所有文本
all_the_data = open('abinfile','rb').read( )
# 二进制文件中的所有数据
为了安全起见,最好还是给打开的文件对象指定一个名字,这样在完成操作之后可以迅速关闭文件,防止一些无用的文件对象占用内存。举个例子,对文本文件读取:
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
不一定要在这里用Try/finally语句,但是用了效果更好,因为它可以保证文件对象被关闭,即使在读取中发生了严重错误。
二.最简单、最快,也最具Python风格的方法是逐行读取文本文件内容,并将读取的数据放置到一个字符串列表中:list_of_all_the_lines = file_object.readlines( )
这样读出的每行文本末尾都带有"\n"符号;如果你不想这样,还有另一个替代的办法,比如:
list_of_all_the_lines = file_object.read( ).splitlines( )
list_of_all_the_lines = file_object.read( ).split('\n')
list_of_all_the_lines = [L.rstrip('\n') for L in file_object]
1、Python
Python(英语发音:/?pa?θ?n/), 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年,Python 源代码同样遵循 GPL(GNU General Public License)协议。
2、基本概念
Python(KK 英语发音:/'pa?θɑn/, DJ 英语发音:/?paiθ?n/)是一种面向对象、直译式计算机程序设计语言,由Guido van Rossum于1989年底发明。
Python如何从文件读取数据
1.1 读取整个文件
要读取文件,需要一个包含几行文本的文件(文件PI_DESC.txt与file_reader.py在同一目录下)
PI_DESC.txt
3.1415926535
8979323846
2643383279
5028841971
file_reader.py
with open("PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
我们可以看出,读取文件时,并没有使用colse()方法,那么未妥善的关闭文件,会不会导致文件收到损坏呢?在这里是不会的,因为我们在open()方法前边引入了关键字with,该关键字的作用是:在不需要访问文件后将其关闭
1.2文件路径
程序在读取文本文件的时候,如果不给定路径,那么它会先在当前目录下进行检索,有时候我们需要读取其他文件夹中的路径,例如:
现在文件PI_DESC.txt存储在python目录的子文件夹txt中
那么我们读取文本内容的代码得修改为:
with open("txt\PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
给open参数传递的参数得给相对路径
在Windows中,使用反斜杠(\),但是由于python中,反斜杠被视为转义字符,在Windows最好在路径开头的单(双)引号前加上r
相对路径:即相对于程序文件的路径
绝对路径:即文本在硬盘上存储的路径
使用绝对路径的程序怎么写呢 ?
with open(r"D:\python\txt\PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
1.3逐行读取
读取文件时,可能需要读取文件中的每一行,要以每一行的方式来检查文件或者修改文件,那么可以对文件对象使用for循环
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line)
程序运行结果如下:
通过运行结果我们可以看出,打印结果中间有很多空白行,这些空白行是怎么来的呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加一个换行符,因此每行末尾就有2个换行符:一个来自文件,另外一个来自print,消除这些换行符,只需要使用方法rstrip()
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line.rstrip())
打印结果
通过运行结果我们可以看出,打印结果中间有很多空白行,这些空白行是怎么来的呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加一个换行符,因此每行末尾就有2个换行符:一个来自文件,另外一个来自print,消除这些换行符,只需要使用方法rstrip()
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line.rstrip())
打印结果
1.4创建一个包含文件各行内容的列表
使用关键字with时,open()返回的文件对象只能在with代码块可用,如果要在with代码块外访问文件的内容,可在with块中将文件各行存储在一个列表,并在with代码块外使用该列表
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()for line in lines:
print(line.rstrip())
1.5使用文件的内容
在上面一节中我们提到把数据提取到内存中,那么我们就可以对数据进行随心所欲的操作了
需要:将圆周率连在一起打印出来(删除空格),并打印其长度
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()pi_str = ''for line in lines:
pi_str += line.strip()print(pi_str.rstrip())print(len(pi_str.rstrip()))
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()pi_str = ''for line in lines:
pi_str += line.strip()print(pi_str.rstrip())print(len(pi_str.rstrip()))
注意最后print语句并没有缩进,如果是缩进的话就会每取一行打印一次
打印效果如下