一、获取文件及目录
<一>、在python中,路径可以接受“/”“\”,这里形象的比喻成撇('posix')和捺('nt')。但是由于“\”在python中是作为转义符使用,所以在路径中使用“\”时,要写成“\\”。
因此在python中,下面这两种写法都是可以接受的。
('posix') "c:/test/my doc"
('nt') "c:\\test\\my doc"
<二>、在python绝对路径的书写中,要注意盘符后面加冒号。例如:"c:\\test/my doc"
<三>、在python中,当前目录、父目录、根目录、子目录的表示分别示例如下:
os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。这个列表以字母顺序。 它不包括 '.' 和'..' 即使它在文件夹中。只支持在 Unix, Windows 下使用。
1、当前目录:os.listdir(".") f1 = open('xuefeng.txt','w')
2、父目录:os.listdir("..") f1 = open('../xuefeng.txt','w')
3、根目录写法一:os.listdir('/') f1 = open('/xuefeng.txt','w')
4、根目录写法二:os.listdir('\\') f1 = open('\\xuefeng.txt','w')
5、子目录:os.listdir('mytext') f1 = open('mytext/xuefeng.txt','w') #假设当前目录中有一个名为mytext的子目录要访问
os.path.isdir()和os.path.isfile()使用误区:
#判断是否存在以及为txt文本,后续处理
for file in os.listdir(path):
if os.path.isfile(file) and os.path.splitext(file)[1] == '.txt':
结果if一直为假,
需要了解:
os.path.isfile(path)中path是路径.....
而上面传的是一个文件名.
解决方法:
>>> os.path.isfile(os.path.join(path,files[1]))
True
二、操作文件和目录
# 查看当前目录的绝对路径:
>>> os.path.abspath('.')
'/Users/michael'
# 在某个目录下创建一个新目录,首先把新目录的完整路径表示出来:
>>> os.path.join('/Users/michael', 'testdir')
'/Users/michael/testdir'
# 然后创建一个目录:
>>> os.mkdir('/Users/michael/testdir')
# 删掉一个目录:
>>> os.rmdir('/Users/michael/testdir')
#拆分路径
>>> os.path.split('/Users/michael/testdir/file.txt')
('/Users/michael/testdir', 'file.txt')
#获得扩展名
>>> os.path.splitext('/path/to/file.txt')
('/path/to/file', '.txt')
以上只对字符串操作,并不要求含有真实文件
以上只对字符串操作,并不要求含有真实文件
以上只对字符串操作,并不要求含有真实文件
以下要求含有test.txt文件
# 对文件重命名:
>>> os.rename('test.txt', 'test.py')
# 删掉文件:
>>> os.remove('test.py')
#复制可以使用 shutil模块提供了copyfile()的函数
#过滤文件(如列出所有目录)
>>> [x for x in os.listdir('.') if os.path.isdir(x)]
['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...]
#过滤文件,如列出.py文件
>>> [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
['apis.py', 'config.py', 'models.py', 'pymonitor.py', 'test_db.py', 'urls.py', 'wsgiapp.py']
python遍历文件夹
import os
import os.path
rootdir = “d:\data” # 指明被遍历的文件夹
for parent,dirnames,filenames in os.walk(rootdir):
#三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
for dirname in dirnames: #输出文件夹信息
print "parent is:" + parent
print "dirname is" + dirname
for filename in filenames: #输出文件信息
print "parent is": + parent
print "filename is:" + filename
print "the full name of the file is:" + os.path.join(parent,filename) #输出文件路径信息
#windows下为:d:\data\query_text\EL_00154
在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径
#listdir方法
def searchfile(path,k):
import os
filelist=os.listdir(path)
for x in filelist:
if k in x:
print(os.path.join(path,x))#这边是把x添加到路径后面,不能直接打印x
path= input('Directory: ')
k= input('search: ')
searchfile(path,k)
#遍历方法1
[filename for t in os.walk(search_dir) for filename in t[2] if search_str in os.path.splitext(filename)[0]]
#遍历方法2
import os, logging
def search(s):
rootdir = '.' # 指明被遍历的文件夹
for parent,dirnames,filenames in os.walk(rootdir): #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
for filename in filenames: #输出文件信息
#print "filename is:" + filename
if filename.find(s) != -1:
print "the full path of the file is:" + os.path.abspath(os.path.join(parent,filename)) #输出文件路径信息
if __name__ == '__main__':
search('input')
#使用调试logging方法
import os, pdb, logging
logging.basicConfig(level=logging.DEBUG)
def search_dir(path, L):
current_dir = os.listdir(path)
pdb.set_trace()
for n in current_dir:
pdb.set_trace()
new_path = os.path.join(path, n)
if os.path.isfile(new_path): # 需传入路径而非仅仅文件名,否则是FALSE
logging.debug('%s is a file.' % n)
L.append(new_path)
else:
search_dir(new_path, L)
return L
def search(s):
L = search_dir('.', [])
# pdb.set_trace()
for file in L:
pdb.set_trace()
if file.find(s) != -1:
logging.info('找到包含%s的文件路径:%s' % (s, os.path.abspath(file)))
# os.path.abspath(url) 并非返回url真正完整的绝对路径,只是将当前目录与url进行join操作
# 例如,当前目录为 D:/workplace
# url是 test.txt,实际是在 ./aaa/test.txt
# 但该函数返回的是 D:/workplace/test.txt
if __name__ == '__main__':
search('test')
实现邮箱格式
^表示行的开头,^\d表示必须以数字开头。
$表示行的结束,\d$表示必须以数字结束。
import re
def regex(s, t):
# re_mail=re.compile(t)
for x in s:
m = re.match(t, x)
n = m.groups()
if n[2]=='com':
print('%s is mail' % x)
else:
print('%s is failed' % x)
ke = r'^([0-9a-zA-Z\_\.]*)\@([a-zA-Z\_\.]*)\.([0-9a-zA-Z\_\.]{3})$'
s1 = ['[email protected]', '[email protected]']
regex(s1, ke)
三、遇到BUG(IOError: [Errno 22] invalid mode ('r') or filename: 'E:\\python_script\x08.txt')
#错误行
with open('E:\python_script\10.txt','r') as f:
这种错误的出现是在使用built-in函数file()或者open()的时候。
一是因为文件的打开模式不对,二是文件名有问题。
前者的话只需要注意文件是否可读或者可写就可以了。
后者则是与文件路径相关的问题,需要在文件名前加r或者R转义,如:file(r"e:\Test.txt",'r').或者将反斜杠\变成两个,如file("e:\\Test.txt",'r').