python入坑进阶第二步:读写文件(window系统为例)

python入坑进阶第二步:读写文件(window系统为例)1 文件与文件路径 1 os path join 将传递的字符串 返回成一个文件路径的字符串 gt gt gt import os gt gt gt os path join program python favorite

大家好,我是讯享网,很高兴认识大家。

1、文件与文件路径

1)os.path.join():将传递的字符串,返回成一个文件路径的字符串。
>>> import os >>> os.path.join('program','python','favorite') 'program\\python\\favorite' >>> 

讯享网
注意\,其中有一个倒斜杠起转义作用。
这里还有一个问题,博主没有弄清楚,有大神知道的,麻烦评论区留言,万分感谢
讯享网>>> import os >>> os.path.join('D:','python','favorite')#结果和预料的不太一样!! 'D:python\\favorite' >>> os.path.join('D:\\','python','favorite') 'D:\\python\\favorite' 

2)os.getcwd()和os.chdir()

os.getcwd():获取当前工作路径的字符串。

os.chdir():改变当前工作路径。

>>> import os >>> os.getcwd() 'D:\\Python3.3.2' >>> os.chdir('D:\\python\\test') Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> os.chdir('D:\\python\\test') FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'D:\\python\\test' >>> D盘新建一个文件夹python,在python文件夹新建test文件夹。 >>> os.chdir('D:\\python\\test') >>> os.getcwd() 'D:\\python\\test' >>> 

3)绝对路径和相对路径

目录文件:D:\python\test\test.py

当前目录:D:\python\test 为例:

绝对路径 相对路径
D: …\…\
D:\python …\
D:\python:\test .\
D:\python\test\test.py .\test.py

4)os.makedirs()创建新文件夹

讯享网>>> import os >>> os.getcwd() 'D:\\python\\test' >>> os.chdir('D:\\python\\new') Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> os.chdir('D:\\python\\new') FileNotFoundError: [WinError 2] 系统找不到指定的文件。: 'D:\\python\\new' >>> os.makedirs('D:\\python\\new') >>> os.chdir('D:\\python\\new') >>> os.getcwd() 'D:\\python\\new' >>> 

5)绝对路径和相对路径之间的相护转换和判断

①:相对路径转绝对路径— os.path.abspath(path)
>>> import os >>> os.getcwd() 'D:\\python\\new' >>> os.path.abspath('..\\') 'D:\\python' >>> 
②:绝对路径转相对路径— os.path.relpath(path,start)
讯享网>>> import os >>> os.getcwd() 'D:\\python\\new' >>> #不提供start,使用当前工作目录作为开始路径 >>> os.path.relpath('D:\\python') '..' >>> #提供start,start的路径为D:\\python >>> os.path.relpath('D:\\python','D:\\python') '.' >>> 
③:相对/绝对路径的判断— os.path.isabs(path)

绝对路径:D:\python\test 返回 True

相对路径:…\ 返回 False

>>> import os >>> os.path.isabs('..\\') False >>> os.path.isabs('D:\\python\\test') True >>> 
6)查看文件大小和文件夹内容
①:os.listdir(path)— 返回该文件名下的文件名列表
讯享网>>> import os >>> os.listdir('D:\\python\\test') ['exit.py', 'hello.py', 'test.py'] >>> 
②:os.path.getsize(path)— 返回path参数中文件的字节数
>>> import os >>> os.path.getsize('D:\\python\\test\\test.py') 296 >>> os.path.getsize('D:\\python\\test\\hello.py') 352 >>> 
7)检查路径的有效性
①:os.path.exists(path)
如果path参数所指的文件或文件夹存在,调用方法将返回True,否则False
讯享网>>> import os >>> os.listdir('D:\\python') ['new', 'test'] >>> os.path.exists('D:\\python\\new') True >>> os.path.exists('D:\\python\\old') False >>> os.listdir('D:\\python\\test') ['exit.py', 'hello.py', 'test.py'] >>> os.path.exists('D:\\python\\test\\exit.py') True >>> os.path.exists('D:\\python\\test\\start.py') False >>> 
②:os.path.isfile(path)
>>> import os >>> os.listdir('D:\\python') ['new', 'test'] >>> os.path.isfile('D:\\python\\new') False >>> os.path.isfile('D:\\python\\old') False >>> os.listdir('D:\\python\\test') ['exit.py', 'hello.py', 'test.py'] >>> os.path.isfile('D:\\python\\test\\test.py') True >>> os.path.isfile('D:\\python\\test\\abc.py') False >>> 
③:os.path.isdir(path)
讯享网>>> import os >>> os.listdir('D:\\python') ['new', 'test'] >>> os.path.isdir('D:\\python\\new') True >>> 

2、文件读写过程

1)读写文件的三个步骤:
1、调用open()函数,返回一个File对象。 2、调用File对象的read()或write()方法 2、调用File对象的close()方法,关闭该文件。 
2)open()函数之打开文件的三种模式
①:读模式{open(‘文件路径’,‘r’)或open(‘文件路径’)}:
讯享网>>> file=open('D:\\python\\new\\hello.txt') >>> file=open('D:\\python\\new\\hello.txt','r') 
②:写模式{open(‘文件路径’,‘w’)}:
>>> file=open('D:\\python\\new\\hello.txt','w') 
③:添加模式{open(‘文件路径’,‘a’)}:
讯享网>>> file=open('D:\\python\\new\\hello.txt','a') 
3)读取文件内容之read()函数和readlines()函数

D:\python\new\hello.txt 文本内容如下:

hello hi happy day 

read()函数读取文件:返回格式为字符串


讯享网

讯享网>>> file=open('D:\\python\\new\\hello.txt') >>> file.read() 'hello\nhi\nhappy day' 

readlines()函数读取文件:返回格式为字符串列表

>>> file=open('D:\\python\\new\\hello.txt') >>> file.readlines() ['hello\n', 'hi\n', 'happy day'] 
4)write()函数之写入文件
如果传递给open()的文件名不存在,写模式和添加模式都会创建一个新的空文件夹。

写模式下写入文件

讯享网>>> file=open('D:\\python\\new\\hello.txt') >>> file.read() 'hello\nhi\nhappy day' >>> file=open('D:\\python\\new\\hello.txt','w') >>> file.write('new file details') 16 >>> #在写入文件时,必须调用close()方法,然后才能再次打开文件,否则报错!!!! >>> file.close() >>> file=open('D:\\python\\new\\hello.txt') >>> file.read() 'new file details' 
这里的16是返回写入字符的个数。

添加模式下写入文件

>>> file=open('D:\\python\\new\\hello.txt') >>> file.read() 'new file details' >>> file=open('D:\\python\\new\\hello.txt','a') >>> file.write('\n new file detail add') 21 >>> #在写入文件时,必须调用close()方法,然后才能再次打开文件,否则报错!!!! >>> file.close() >>> file.read() 'new file details\n new file detail add' >>> file=open('D:\\python\\new\\hello.txt') >>> file.readlines() ['new file details\n', ' new file detail add'] >>> 
write()方法不会像print()方法那样,在字符串的末尾自动添加换行字符!!!!

3、用shelve模块保存变量

1)保存变量
讯享网>>> import shelve >>> file=shelve.open('D:\\python\\new\\mydata') >>> name=['Amy','Sum','DaMing'] >>> file['name']=name >>> file.close() 

此时会在D:\python\new目录下生成三个新文件(二进制的shelf文件):

mydata.bak; mydata.dat; mydata.dir 

如图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FaFQGxjn-1642758905200)(C:\Users\17216\AppData\Roaming\Typora\typora-user-images\image-20220119213203524.png)]

2)读取变量
讯享网>>> import shelve >>> file=shelve.open('D:\\python\\new\\mydata') >>> file['name'] ['Amy', 'Sum', 'DaMing'] >>> file.close() 
3)查看存储shelf值的键和值

新存储一个变量:age

>>> file=shelve.open('D:\\python\\new\\mydata') >>> age=['16','17','18'] >>> file['age']=age >>> file['age'] ['16', '17', '18'] >>> file.close() 

查看存储shelf值的键和值:shelf中的键和值类似列表的键和值,但不是真正的列表,所以需要将其list()函数,取得列表形式。

讯享网>>> file=shelve.open('D:\\python\\new\\mydata') >>> file.keys() KeysView(<shelve.DbfilenameShelf object at 0x000000000356E208>)#返回的是键的存储地址 >>> list(file.keys()) ['name', 'age'] >>> file.values() ValuesView(<shelve.DbfilenameShelf object at 0x000000000356E208>)#返回的是值的存储地址 >>> list(file.values()) [['Amy', 'Sum', 'DaMing'], ['16', '17', '18']] >>> file.close() 

小讯
上一篇 2025-03-07 15:29
下一篇 2025-03-09 09:26

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/100102.html