怎么读取整个文件 python
Python 读写文本文件
首先需要注意的是,txt文件是具有字符编码的,不同的txt字符编码可能不同。具体是什么编码,可以用 notepad++ 等文本编辑器查看。
读取文件建议使用 with...as... 结构,可以自动关闭文件。
with open(text.txt, r) as f:
text = f.read()
print(text)
如果不用 with...as... 则必须手动关闭文件:
f = open(text.txt, r)
text = f.read()
f.close()
print(text)
如果读取的文件含有中文,使用内置的open可能会报错,这个时候要用到codecs模块:
import codecs
with codecs.open(text.txt, r, encoding=utf-8) as f:
text = f.read()
print(text)
(假设 text.txt 是 utf-8 编码)
用python实现一个本地文件搜索功能。
import re,os
import sys
def filelist(path,r,f):
function to find the directions and files in the given direction
according to your parameters,fileonly or not,recursively find or not.
file_list = []
os.chdir(path)
filename = os.listdir(path)
if len(filename) == 0:
os.chdir(os.pardir)
return filename
if r == 1: ##
if f == 0: # r = 1, recursively find directions and files. r = 0 otherwise.
for name in filename: # f = 1, find files only, f = 0,otherwise.
if os.path.isdir(name): ##
file_list.append(name)
name = os.path.abspath(name)
subfile_list = filelist(name,r,f)
for n in range(len(subfile_list)):
subfile_list[n] = '\t'+subfile_list[n]
file_list += subfile_list
else:
file_list.append(name)
os.chdir(os.pardir)
return file_list
elif f == 1:
for name in filename:
if os.path.isdir(name):
name = os.path.abspath(name)
subfile_list = filelist(name,r,f)
for n in range(len(subfile_list)):
subfile_list[n] = '\t'+subfile_list[n]
file_list += subfile_list
else:
file_list.append(name)
os.chdir(os.pardir)
return file_list
else:
print 'Error1'
elif r == 0:
if f == 0:
os.chdir(os.pardir)
return filename
elif f == 1:
for name in filename:
if os.path.isfile(name):
file_list.append(name)
os.chdir(os.pardir)
return file_list
else:
print 'Error2'
else:
print 'Error3'
'''
f = 0:list all the files and folders
f = 1:list files only
r = 1:list files or folders recursively,all the files and folders in the current direction and subdirection
r = 0:only list files or folders in the current direction,not recursively
as for RE to match certern file or dirction,you can write yourself, it is easier than the function above.Just use RE to match the result,if match,print;else,pass
|