python文件和文件夹訪问File and Directory Access

http://blog.csdn.net/pipisorry/article/details/47907589

os.path — Common pathname manipulations

都是和路径指定的文件,文件夹,和路径字符串有关系的函数

os.path.isdir(name)           推断name是不是一个文件夹,name不是文件夹就返回false
os.path.isfile(name)           推断name是不是一个文件。不存在name也返回false

os.path.islink(name)         推断nama是不是一个链接文件
os.path.exists(name)         推断是否存在文件或文件夹name
os.path.getsize(name)       获得文件大小,假设name是文件夹返回0L
os.path.abspath(name)     获得绝对路径

os.path.realpath 获取文件绝对路径
os.path.normpath(path)    规范path字符串形式
os.path.split(name)           切割文件名称与文件夹(其实,假设你全然使用文件夹。它也会将最后一个文件夹作为文件名称而分离,同一时候它不会推断文件或文件夹是否存在)

os.path.splitext()               分离文件名称与扩展名
os.path.join(path,name)    连接文件夹与文件名称或文件夹
os.path.basename(path)   返回文件名称
os.path.dirname(path)       返回文件路径

os.path.basename(path)
Return the base name of pathname path. This is the second half of the pair returned by split(path).
Note that the result of this function is different from the Unix basename program; where basename for ’/foo/bar/’ returns ’bar’, the basename() function returns an empty string (”).
os.path.dirname(path)
Return the directory name of pathname path. This is the first half of the pair returned by split(path).

os.path.abspath(name)     获得绝对路径
realpath = os.path.realpath(filename)
print realpath
# output
# C:xxxpyfunc est.txt

os.path.split()

返回一个路径的文件夹名和文件名称。

  1. >>> os.path.split('/home/shirley/myself/code/icbc.txt')  
  2. ('/home/shirley/myself/code', 'icbc.txt')  

Note:path.split()中文件夹參数对结果的影响

print(path.split(r'E:minejava_workspaceAMC_masterDataInputcorpus_NP'))

返回('E:\mine\java_workspace\AMC_master\Data\Input', 'corpus_NP'),而

print(path.split(r'E:minejava_workspaceAMC_masterDataInputcorpus_NP/'))

返回('E:\mine\java_workspace\AMC_master\Data\Input\corpus_NP', '')

os.path.splitext(path)
Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored;
splitext(’.cshrc’) returns (’.cshrc’, ”). Changed in version 2.6: Earlier versions could produce an empty root when the only period was the first character.

os.path.join(path1, [path2, [...]])
Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) inserted between components, unless path2 is empty. Note that onWindows, since there is a current directory for each drive,os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:foo.

[os.path — Common pathname manipulations]

[python系统模块sys、os及应用]

os — Files and Directories

os.getcwd()

函数得到当前工作文件夹。即当前Python脚本工作的文件夹路径。

Return a string representing the current working directory. Availability: Unix, Windows.

os.curdir                返回但前文件夹('.')
os.chdir(dirname)  改变工作文件夹到dirname

os.listdir(path)              

 返回指定文件夹下的全部文件和文件夹名 

Note:listdir会将保护的操作系统文件list出来,如windows下的desktop.ini文件

Return a list containing the names of the entries in the directory. The list is in arbitrary order. It does not include the special entries ’.’ and ’..’ even if they are present in the directory. Availability: Unix,Windows. Changed in version 2.3: OnWindows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects.

os.makedirs(path, [mode])

os.makedirs(os.path.join(WORK_DIR, 'data_analysis/'), exist_ok=True)
os.makedirs("./input", exist_ok=True)     #能够使用相对路径
exist_ok=True则假设文件夹或文件不存在则创建。否则不创建。相当于加了一个exist推断。

Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Throws an error exception if the leaf directory already exists or cannot be created. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.
Note: makedirs() will become confused if the path elements to create include os.pardir. New in version 1.5.2.Changed in version 2.3: This function now handles UNC paths correctly.

os.walk(top, [topdown=True, [onerror=None, [followlinks=False]]])

os.walk是一个generator函数。Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames,filenames).......每次能够得到一个三元tupple。当中第一个为起始路径,第二个为起始路径下的文件夹。第三个是起始路径下的文件。

举比例如以下:

>>> x=os.walk('/home/tiny/workspace/py')
>>> x
<generator object walk at 0x8ef652c>
>>>for i in x:
... i
... 
('/home/tiny/workspace/py', ['2', '1'], ['.allfile.py.swp', 'allfile.py', 'list_get.py', 'test.py', 'tags', 'log.txt'])
('/home/tiny/workspace/py/2', [], ['fib.py', 'djcoding.py', 'drectory_travel.py', 'foo.py'])
('/home/tiny/workspace/py/1', [], ['timetest2.py', 'timetest.py'])

os.rmdir(path, *, dir_fd=None)

Remove (delete) the directory path. Only works when the directory isempty, otherwise, OSError is raised.

os.removedirs(name)

递归删除空文件夹(包含父文件夹)。子文件夹非空出错。
递归删除文件夹(全部子文件夹,包容非空子文件夹)
__import__('shutil').rmtree(DATA_DIR)

[shutil.rmtree(path, ignore_errors=False, onerror=None)]

os.remove(path, *, dir_fd=None)

删除文件:Remove (delete) the file path. If path is a directory, OSError israised.

os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)

改动文件权限

[Files and Directories*]

[The Python Library Reference Release2.6 - 16.1.4]

[python系统模块sys、os及应用]

皮皮Blog

python创建新文件

创建某个文件:直接使用写模式打开就能够了

with open(json_file, 'w', encoding='utf-8') as out_file
可是假设文件名称中带有路径,而路径不存在就会报错:FileNotFoundError: [Errno 2] No such file or directory: 'word_seg\0'

这时要先推断路径是否存在,若不存在要先创建路径。再去新建文件

os.makedirs(os.path.dirname(json_file), exist_ok=True)
with open(json_file, 'w', encoding='utf-8') as out_file

注意,假设要创建的文件带有路径,而文件名称又是一个路径时,用写w模式打开会出错,由于这时打开的是一个路径。将一个路径当成文件打开就会出现例如以下错误:

PermissionError: [Errno 13] Permission denied:

其解决方法还是上面的,先推断路径存在否,再创建文件。

皮皮Blog


shutil

 — High-level file operations

shutil.copyfile(src, dst, *, follow_symlinks=True)

shutil.copy(src, dst, *, follow_symlinks=True)
shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)

shutil.rmtree(path, ignore_errors=False, onerror=None)

Delete an entire directory tree; path must point to a directory (but not asymbolic link to a directory). If ignore_errors is true, errors resultingfrom failed removals will be ignored; if false or omitted, such errors arehandled by calling a handler specified by onerror or, if that is omitted,they raise an exception.

递归删除文件夹(全部子文件夹。包容非空子文件夹):
if os.path.exists(os.path.join(CWD, 'middlewares/metadata')):
    __import__('shutil').rmtree(os.path.join(CWD, 'middlewares/metadata'))
shutil.move(src, dst, copy_function=copy2)
shutil.chown(path, user=None, group=None)
[shutil — High-level file operations]

Glob()查找文件

大多Python函数有着长且具有描写叙述性的名字。可是命名为glob()的函数你可能不知道它是干什么的除非你从别处已经熟悉它了。


它像是一个更强大版本号的listdir()函数

它能够让你通过使用模式匹配来搜索文件。
import glob
# get all py files
files = glob.glob('*.py')
print files

# Output
# ['arg.py', 'g.py', 'shut.py', 'test.py']

import glob
# get all py files
files = glob.glob('*.py')
print files

# Output
# ['arg.py', 'g.py', 'shut.py', 'test.py']
 
你能够像以下这样查找多个文件类型:

import itertools as it, glob
def multiple_file_types(*patterns):
    return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns)
for filename in multiple_file_types("*.txt", "*.py"): # add as many filetype arguements
    print filename

# output
#=========#
# test.txt
# arg.py
# g.py
# shut.py
# test.py
假设你想得到每一个文件的绝对路径。你能够在返回值上调用realpath()函数:
import itertools as it, glob, os
def multiple_file_types(*patterns):
    return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns)
 
for filename in multiple_file_types("*.txt", "*.py"): # add as many filetype arguements
    realpath = os.path.realpath(filename)
    print realpath

# output
#=========#
# C:xxxpyfunc est.txt
# C:xxxpyfuncarg.py
# C:xxxpyfuncg.py

# C:xxxpyfuncshut.py
# C:xxxpyfunc est.py

[glob — Unix style pathname pattern expansion]

fnmatch 实现shell风格模式匹配特定字符

fnmatch.fnmatch(names, pattern)

測试name是否匹配pattern,返回true/false。

以下的样例列出了当前文件夹中的全部py文件:

>>>import fnmatch
>>>import os
>>>for file in os.listdir('.'):
... if fnmatch.fnmatch(file, '*.py'):
... print file
... 
allfile.py
list_get.py
test.py

假设操作系统是大写和小写不敏感的,则在fnmatch.fnmatch()中全部的參数将被统一格式为全部大写或全部小写。


fnmatch.fnmatchcase( names, pattern)

与平台无关的大写和小写敏感的fnmatch.fnmatch

fnmatch.filter(names, pattern)

实现列表特殊字符的过滤或筛选,返回符合匹配模式的字符列表,例:

>>> files=['tags', 'readme.txt', 'allfile.py', 'test.py']
>>> fnmatch.filter(files, '*.py')
['allfile.py', 'test.py']
>>> fnmatch.filter(files, '[tx]*')
['tags', 'test.py']
>>> fnmatch.filter(files, '[tr]*')
['tags', 'readme.txt', 'test.py']
>>> fnmatch.filter(files, '*[tr]*')
['tags', 'readme.txt', 'test.py']
>>> fnmatch.filter(files, '?[a]*')
['tags']

注意: [seq] 匹配单个seq中的随意单个字符

fnmatch.translate(pattern)

翻译模式。 fnmatch将这样的全局模式转换成一个正则式。 然后使用re模块来比較名字和模式。 translate() 函数是一个公共API用于将全局模式转换成正则式。

>>>import fnmatch
>>> pattern='*.py'
>>>print fnmatch.translate(pattern)
.*.py(?ms)
  • unix shell风格匹配方式
  1. *表示匹配不论什么单个或多个字符
  2. ?

    表示匹配单个字符

  3. [seq] 匹配单个seq中的随意单个字符
  4. [!seq]匹配单个不是seq中的随意单个字符

[fnmatch — Unix filename pattern matching]

python文件读取模块 - fileinput模块

fileinput模块能够对一个或多个文件里的内容进行迭代、遍历等操作。用fileinput对文件进行循环遍历,格式化输出,查找、替换等操作,非常方便。
Python的精髓在于模块的运用,运用C的思维,非常难学好Python。

fileinput模块能够轻松的遍历文本的全部行,能够实现相似pythonsome_script.py file_1.txt file_2.txtfile_2.txt的模式。
实际上就是一个readline()。仅仅只是能够实现很多其他的功能
该模块的input()函数有点相似文件readlines()方法,差别在于:
前者是一个迭代对象。即每次仅仅生成一行,须要用for循环迭代。后者是一次性读取全部行。

在碰到大文件的读取时。前者无疑效率更高效。


【基本格式】

fileinput.input([files[, inplace[, backup[, bufsize[, mode[, openhook]]]]]])

【默认格式】

fileinput.input (files=None, inplace=False, backup='', bufsize=0, mode='r', openhook=None)

  1. files:                  #文件的路径列表,默认是stdin方式,多文件['1.txt','2.txt',...]  
  2. inplace:                #是否将标准输出的结果写回文件,默认不代替  
  3. backup:                 #备份文件的扩展名,仅仅指定扩展名。如.bak。假设该文件的备份文件已存在,则会自己主动覆盖。  
  4. bufsize:                #缓冲区大小,默觉得0,假设文件非常大,能够改动此參数,一般默认就可以  
  5. mode:                   #读写模式,默觉得仅仅读  
  6. openhook:               #该钩子用于控制打开的全部文件。比方说编码方式等;  

fileinput模块中的经常使用函数

fileinput.input()       #返回能够用于for循环遍历的对象  

fileinput.filename()    #返回当前文件的名称  
fileinput.lineno()      #返回当前已经读取的行的数量(或者序号)  
fileinput.filelineno()  #返回当前读取的行的行号  
fileinput.isfirstline() #检查当前行是否是文件的第一行  
fileinput.isstdin()     #推断最后一行是否从stdin中读取  
fileinput.close()       #关闭队列

[fileinput — Iterate over lines from multiple input streams]

[Python中fileinput模块介绍]

[python文件替代fileinput模块]


linecache

读取文件某一行的内容(測试过1G大小的文件,效率还能够)

import linecache

count = linecache.getline(filename,linenum)

str = linecache.getlines(filename)    #str为列表形式,每一行为列表中的一个元素
Note:linecache是专门支持读取大文件,并且支持行式读取的函数库。 linecache预先把文件读入缓存起来。后面假设你訪问该文件的话就不再从硬盘读取。

读取文件之后你不须要使用文件的缓存时须要在最后清理一下缓存。使linecache.clearcache()清理缓存,释放缓存。

这个模块是使用内存来缓存你的文件内容。所以须要耗费内存,打开文件的大小和打开速度和你的内存大小有关系。

python计算文件的行数和读取某一行内容的实现方法

python从第二行開始读文件到k行

1 data = open(filename)
next(data) #或者data.readline()
for e in data:
    print(e)

2 lines = f.readlines()[1:]

for l in lines:

    print(l)

3. a=linecache.getlines('a.txt')[0:-1]

python从第i行開始读文件到第j行

1. 获取a.txt文件里第1-4行的内容

>>> a=linecache.getlines('a.txt')[0:4]

2. lnum = 0
with open('pit.txt', 'r') as fd:
    for line in fd:
        lnum += 1;
        if (lnum >= 10) && (lnum <= 13):
            print line
[python linecache模块读取文件使用方法具体解释]
《python cookbook》中文版第二版 2.4节从文件里读取指定的行 (Luther Blissett)

tempfile模块

用于生成暂时文件和文件夹

tempfile.mkdtemp(suffix=None, prefix=None, dir=None)

Creates a temporary directory in the most secure manner possible. Thereare no race conditions in the directory’s creation. The directory isreadable, writable, and searchable only by the creating user ID.

The user of mkdtemp() is responsible for deleting the temporarydirectory and its contents when done with it.

The prefix, suffix, and dir arguments are the same as formkstemp().mkdtemp() returns the absolute pathname of the new directory.

如:

import tempfile

path = tempfile.mkdtemp(suffix='.txt', prefix='pi')
print(path)
/tmp/piv5dwqs01.txt

with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'

[tempfile — Generate temporary files and directories]

皮皮Blog


其他相关库

[pathlib — Object-oriented filesystem paths]

[stat — Interpreting stat() results]

[filecmp — File and Directory Comparisons]

[macpath — Mac OS 9 path manipulation functions]

from:http://blog.csdn.net/pipisorry/article/details/47907589

ref: [File and Directory Access]

[https://docs.python.org/3/library/os.html]

[The Python Library Reference Release2.6 - 11.1]


原文地址:https://www.cnblogs.com/zsychanpin/p/6821875.html