Python3学习笔记:文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/daihuimaozideren/article/details/80817386

目录操作

os模块提供了很多方法来完成常见的目录操作。本节我们介绍几个常用方法。至于其他方法,可以通过dir(),help()了解。

示例为目录的创建和删除操作。

import os

dirname=os.path.abspath('.')+'\\txt\\'
 
if not os.path.exists(dirname):
    os.makedirs(dirname)
    print("create dir "+dirname)
else:
    os.removedirs(dirname)
    print("remove dir "+dirname)

连续执行两次,结果分别为

C:\E\FACE\PythonSpace\helloworld\src\file\txt\ is not a dir
create dir C:\E\FACE\PythonSpace\helloworld\src\file\txt\
C:\E\FACE\PythonSpace\helloworld\src\file\txt\ is a dir
remove dir C:\E\FACE\PythonSpace\helloworld\src\file\txt\

我们可以使用help方法,查看os所提供的方法该如何使用。

help(os.path.isdir) #isdir用于判断目录是否存在
help(os.path.exists) #exists用于判断路径是否存在
help(os.path.abspath) #abspath用于获取当前的绝对路径
help(os.makedirs) #makedirs用于创建(多级)目录
help(os.removedirs) #removedirs用于删除目录

对应输出如下

Help on built-in function _isdir in module nt:

_isdir(path, /)
    Return true if the pathname refers to an existing directory.

Help on function exists in module genericpath:

exists(path)
    Test whether a path exists.  Returns False for broken symbolic links

Help on function abspath in module ntpath:

abspath(path)
    Return the absolute version of a path.

Help on function makedirs in module os:

makedirs(name, mode=511, exist_ok=False)
    makedirs(name [, mode=0o777][, exist_ok=False])
    
    Super-mkdir; create a leaf directory and all intermediate ones.  Works like
    mkdir, except that any intermediate path segment (not just the rightmost)
    will be created if it does not exist. If the target directory already
    exists, raise an OSError if exist_ok is False. Otherwise no exception is
    raised.  This is recursive.

Help on function removedirs in module os:

removedirs(name)
    removedirs(name)
    
    Super-rmdir; remove a leaf directory and all empty intermediate
    ones.  Works like rmdir except that, if the leaf directory is
    successfully removed, directories corresponding to rightmost path
    segments will be pruned away until either the whole path is
    consumed or an error occurs.  Errors during this latter phase are
    ignored -- they generally mean that a directory was not empty.

需要注意的是,在删除目录时,若目录不为空,则会报错。

OSError: [WinError 145] The directory is not empty: 'C:\\E\\FACE\\PythonSpace\\helloworld\\src\\file\\txt\\sub\\'

文件操作

文件操作相对简单。来看示例。

dirname=os.path.abspath('.')+'\\txt\\sub\\'
filename='1.txt'
content=['hello\n','breakloop\n','bye']

if not os.path.isfile(os.path.join(dirname,filename)):
    print(filename +" do not existed")
    file=open(os.path.join(dirname,filename),'x')
    file.writelines(content)
    file.close()
else:
    print(filename +" existed")
    file=open(os.path.join(dirname,filename),'r+')   
    contentlist=list(file)
    print(contentlist)
    file.close()
    os.remove(os.path.join(dirname,filename))

连续执行两次,结果为

1.txt do not existed
1.txt existed
['hello\n', 'breakloop\n', 'bye']

os.path.join(dirname,filename),等同于dirname+filename,将目录路径与文件名,组成一个合法路径。

os.remove用于删除文件。

open方法用于打开或创建一个文件。该方法将返回一个文件迭代对象,通过该对象完成文件的读写操作。

open方法原型如下,其中file为必要参数,其他都为optional。

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

open方法中,还要一个参数比较重要,就是mode。

 mode有以下取值:

    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)
当文件不存在时,必须给予写权限才能创建。

此外,对于open中的其他参数,help可以给出较为详细的解释。

本节所讲的文件操作,适用于文本文件和二进制文件(图片,音频等),对于特殊类型的文件,例如excel等,并不包含。

猜你喜欢

转载自blog.csdn.net/daihuimaozideren/article/details/80817386
今日推荐