Python入门学习笔记(五)——文件、文件系统

Python学习(五)

目录

Python学习(五)

Python之文件

打开文件

文件对象方法

Python之文件系统

OS(Operating System)操作系统模块

os.path模块


Python之文件

打开文件

    open(file,mode=‘r’,…… )

                     r:以只读模式打开文件(默认)

                     w:以写入模式打开文件,会覆盖已经存在的文件

                     x:如果文件已经存在,使用此模式打开将会引发异常

                     a:以写入模式打开,如果文件存在,在末尾追加写入

                     b:以二进制模式打开文件

                     t:以文本模式打开(默认)

                     +:可读写模式(添加到其他模式中使用)

                     U:通用换行符支持

注:合法的mode有: r、rb、r+、rb+、w、wb、w+、wb+、a、ab、a+、ab+

>>> f = open("E:\\test.txt")
>>> f
<_io.TextIOWrapper name='E:\\test.txt' mode='r' encoding='cp936'>

文件对象方法

关闭文件

>>> f.close()

读取一行

>>> f.readline()
'第1行:Hello Word!\n'

如果出现以下错误:

Traceback (most recent call last):
  File "", line 1, in
    f.readline()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 2: illegal multibyte sequence

是由于文件编码不一致导致

解决方案: 加上编码限制

f = open("E:\\test.txt",encoding="UTF-8")

Python入门学习笔记(五)——文件、文件系统_第1张图片

返回当前在文件中的位置

>>> f.tell()
36

 

文件读取

f.read(size)——从文件读取size个字节

例如:读出前5个字符

>>> f.read(5)
'第2行:H'

当未给定size或给定负值时,读取剩余的所有字节,然后作为字符串返回

>>> f.read(-1)
'ello Word!\n第3行:Hello Word!\n第4行:Hello Word!\n第5行:Hello Word!\n第6行:Hello Word!\n第7行:Hello Word!\n第8行:Hello Word!'
>>> f.tell()
198

Python入门学习笔记(五)——文件、文件系统_第2张图片

写入文件

f.write(str)——将字符串str写入文件

例如:

>>> f.write("加入新内容")
5

如果出现如下错误:

Traceback (most recent call last):
  File "", line 1, in
    f.write("加入新内容")
io.UnsupportedOperation: not writable

更改文件打开模式为可写入模式:(w会覆盖已有文件内容)

>>> f = open("E:\\test.txt",mode="w",encoding="UTF-8")

Python入门学习笔记(五)——文件、文件系统_第3张图片

f.writelines(seq)——向文件写入字符串序列seq,seq应该是一个返回字符串的可迭代对象

移动文件指针

f.seek(offset,from)——在文件中移动文件指针,从from(0代表文件起始位置,1代表当前位置,2代表文件末尾)偏移offset个字节
例如:

>>> f = open("E:\\test.txt",mode="a+",encoding="UTF-8")
>>> f.seek(0)
0
>>> f.readline()
'第1行:Hello Word!\n'
>>> 

将f转化为列表

>>> list(f)
['第2行:Hello Word!\n', '第3行:Hello Word!\n', '第4行:Hello Word!\n', '第5行:Hello Word!\n', '第6行:Hello Word!\n', '第7行:Hello Word!\n', '第8行:Hello Word!']

把指针定位到初始位置,分行打出

>>> f.seek(0)
0
>>> for each_line in f:
	print(each_line)

	
第1行:Hello Word!

第2行:Hello Word!

第3行:Hello Word!

第4行:Hello Word!

第5行:Hello Word!

第6行:Hello Word!

第7行:Hello Word!

第8行:Hello Word!

   Python入门学习笔记(五)——文件、文件系统_第4张图片

 

Python之文件系统

导入模块:import random

OS(Operating System)操作系统模块

       我们所知道常用的操作系统就有:Windows,Mac OS,Linux,UNIX等,这些操作系统底层对于文件系统的访问工作原理是不一样的,因此你可能就要针对不同的系统来考虑使用哪些文件系统模块。这样的做法是非常不友好且麻烦的,因为这样就意味着当你的程序运行环境一改变,你就要相应的修改大量的代码来应付。

 返回当前的工作目录

>>> import os
>>> os.getcwd()
'E:\\Anaconda'

切换工作目录到E

>>> os.chdir('E:\\')

列举指定目录中的文件名

>>> os.listdir('E:\\')
['$RECYCLE.BIN', '.temp',  'Anaconda', 'BaiduNetdiskDownload', 'CrystalDiskInfo', 'Driver Sweeper', 'eclipsetest', 'Java', 'kinggsoft', 'KuGouCache', 'python-deeplearning', 'QMDownload', 'qqpcmgr_docpro', 'System Volume Information', 'Tencent', 'test.txt', 'xshell']

创建目录(是建立在有a的前提下,如果没有a会报错)

>>> os.mkdir('E:\\a\\b')

建多级目录

>>> os.makedirs(path)

删除单层目录,非空抛异常

>>> os.rmdir('E:\\a\\b')

删除文件

>>> os.remove(path)

删除目录(包括其子目录),非空抛异常

>>> os.removedirs(path)

       >>>os.rename(old,new)

       >>>os.system(‘cmd’)

打开计算器,运行系统的shell命令

>>> os.system('calc')
0

代指当前目录

>>> os.curdir
'.'
>>> os.listdir(os.curdir)
['.nonadmin', 'api-ms-win-core-console-l1-1-0.dll', 'api-ms-win-core-datetime-l1-1-0.dll', 'api-ms-win-core-debug-l1-1-0.dll', 'api-ms-win-core-errorhandling-l1-1-0.dll', 'api-ms-win-core-file-l1-1-0.dll', 'api-ms-win-core-file-l1-2-0.dll', 'api-ms-win-core-file-l2-1-0.dll', 'api-ms-win-core-handle-l1-1-0.dll', 'api-ms-win-core-heap-l1-1-0.dll', 'api-ms-win-core-interlocked-l1-1-0.dll', 'api-ms-win-core-libraryloader-l1-1-0.dll', 'api-ms-win-core-localization-l1-2-0.dll', 'api-ms-win-core-memory-l1-1-0.dll', 'api-ms-win-core-namedpipe-l1-1-0.dll', 'api-ms-win-core-processenvironment-l1-1-0.dll', 'api-ms-win-core-processthreads-l1-1-0.dll', 'api-ms-win-core-processthreads-l1-1-1.dll', 'api-ms-win-core-profile-l1-1-0.dll', 'api-ms-win-core-rtlsupport-l1-1-0.dll', 'api-ms-win-core-string-l1-1-0.dll', 'api-ms-win-core-synch-l1-1-0.dll', 'api-ms-win-core-synch-l1-2-0.dll', 'api-ms-win-core-sysinfo-l1-1-0.dll', 'api-ms-win-core-timezone-l1-1-0.dll', 'api-ms-win-core-util-l1-1-0.dll', 'api-ms-win-crt-conio-l1-1-0.dll', 'api-ms-win-crt-convert-l1-1-0.dll', 'api-ms-win-crt-environment-l1-1-0.dll', 'api-ms-win-crt-filesystem-l1-1-0.dll', 'api-ms-win-crt-heap-l1-1-0.dll', 'api-ms-win-crt-locale-l1-1-0.dll', 'api-ms-win-crt-math-l1-1-0.dll', 'api-ms-win-crt-multibyte-l1-1-0.dll', 'api-ms-win-crt-private-l1-1-0.dll', 'api-ms-win-crt-process-l1-1-0.dll', 'api-ms-win-crt-runtime-l1-1-0.dll', 'api-ms-win-crt-stdio-l1-1-0.dll', 'api-ms-win-crt-string-l1-1-0.dll', 'api-ms-win-crt-time-l1-1-0.dll', 'api-ms-win-crt-utility-l1-1-0.dll', 'concrt140.dll', 'conda-meta', 'condabin', 'cwp.py', 'DLLs', 'envs', 'etc', 'include', 'Lib', 'Library', 'libs', 'LICENSE_PYTHON.txt', 'man', 'Menu', 'msvcp140.dll', 'msvcp140_1.dll', 'msvcp140_2.dll', 'pkgs', 'python.exe', 'python.pdb', 'python3.dll', 'python37.dll', 'python37.pdb', 'pythonw.exe', 'pythonw.pdb', 'qt.conf', 'Scripts', 'share', 'shell', 'sip', 'tcl', 'Tools', 'ucrtbase.dll', 'Uninstall-Anaconda3.exe', 'vccorlib140.dll', 'vcomp140.dll', 'vcruntime140.dll', 'venvlauncher.exe', 'venvwlauncher.exe', 'xlwings32-0.15.10.dll', 'xlwings64-0.15.10.dll', '_conda.exe']

代指上一级目录‘..’

>>> os.pardir
'..'

输出操作系统特定的路径分隔符

>>> os.sep
'\\'

当前平台使用的行终止符(Win:\r\n,Linux:\n)

>>> os.linesep
'\r\n'

指代当前操作系统(posix,nt,mac,os2,ce,java)

>>> os.name
'nt'

os.path模块

去掉目录路径,单独返回文件名

>>> os.path.basename('E:\test.txt')
'\test.txt'

去掉文件名,单独返回路径

>>> os.path.dirname('E:\test.txt')
'E:'

             

合并成目录

>>> os.path.join(path1,……,path2)

例如:

>>> os.path.join('a','b','c')
'a\\b\\c'
>>> os.path.join('c:\\','a') #要自己加上\\
'c:\\a'

 把目录和文件分离(如果path是纯目录,没有文件,会把最后一级目录分离)

>>> os.path.split('E:\test.txt')
('E:', '\test.txt')

分离文件名和扩展名

>>> os.path.splitext('E:\test.txt')
('E:\test', '.txt')

查看文件大小

>>> os.path.getsize("E:\\test.txt")
198

查看文件最近的访问时间

>>> os.path.getatime("E:\\test.txt")
1589029261.6557696
#返回指定文件最近的访问时间(浮点型秒数,可用time模块的gmtime()或localtime()函数来换算

查看文件创建时间

>>> os.path.getctime("E:\\test.txt")
1589026719.4745226

查看文件最新修改时间

>>> os.path.getmtime("E:\\test.txt")
1589029261.6557696

将返回的时间改的更人性化,需要导入time模块

>>> import time
>>> time.gmtime(os.path.getatime("E:\\test.txt"))
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=9, tm_hour=13, tm_min=1, tm_sec=1, tm_wday=5, tm_yday=130, tm_isdst=0)

>>> time.localtime(os.path.getatime("E:\\test.txt"))
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=9, tm_hour=21, tm_min=1, tm_sec=1, tm_wday=5, tm_yday=130, tm_isdst=0)

判断指定路径(目录或文件)是否存在

>>> os.path.exists("E:\\test.txt")
True

判断指定路径是否为绝对路径

>>> os.path.isabs("E:\\test.txt")
True

判断指定路径是否存在且是一个目录

>>> os.path.isdir("E:\\test.txt")
False

判断指定路径是否存在且是一个文件

>>> os.path.isfile("E:\\test.txt")
True

判断指定路径是否存在且是一个符号链接

>>> os.path.islink("E:\\test.txt")
False

判断指定路径是否存在且是一个挂载点

>>> os.path.ismount("E:\\test.txt")
False
>>> os.path.ismount("E:\\")
True

判断path1和path2两个路径是否指向同一文件

>>> os.path.samefile("E:\\test.txt","E:\\test.txt")
True

p.s.

路径:path——"E:\test.txt"

文件:file——"E:\\test.txt"

你可能感兴趣的:(Python)