python怎么读文件夹里的文件(python读取文件)
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
#!/usr/bin/env?python3.6
from?pathlib?import?Path
def?read_all_txt(dirname):
????ss?=?[]
????for?p?in?Path(dirname).rglob('*.txt'):
????????ss.append(p.read_text())
????return?ss
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()