当前位置:   article > 正文

Python之文件操作(含os模块)_pycharm的os库叫什么

pycharm的os库叫什么

 文件的读写操作:

关于文件的读写操作,我们不得不提到系统函数open()函数了。

在使用open()函数时,需要一个变量来接住它,这个变量就相当于一个将Pycharm和文件连接的管道,我们对文件的读写操作都有基于这个管道进行。

open()参数:

open(file,mode,buffering,encoding)

file 是文件路径+文件名,如果该参数有误,则会报错

mode 是读写模式,其值可以是: 'rt' 读取纯文本

                                                      'rb' 以二进制形式读取

                                                      ’wt‘写入纯文本

                                                      'wb'以二进制形式写入

'rb'和'wb'可用于对纯文本,图片,音乐,影像类型的文件进行操作

buffering 是缓存

encoding 是编码方式,encoding='utf-8' 可以读取汉字

文件路径:

绝对路径:也称文件的完整路径。例如:D:\测试(test)文件夹\PY.png

相对路径:相对于当前文件(参照)的路径。 ../   返回上一级目录

读操作:

1.读取纯文本文件时,如果内容含有汉字则会报错

2.在写文件路径的时候,防止误写转义字符,可在字符串前加 r

3.read:可理解为文件被读入了Pycharm

  1. stream = open(r'D:\python\PyCharm\test.txt') #建立通道的动作;防止转义字符,在文件参数上加r
  2. container = stream.read() #读取文件所有内容
  3. result = stream.readable() #判断该文件是否可读
  4. result1 = stream.readline() #若读取过该文件,则返回空行
  5. result2= stream.readlines() #必须是没有读取过的文件
read() 读取所有内容
readable() 判断是否可读,返回值为bool类型
readline() 每次读取一行内容(每行后换行)
readlines() 读取所有行内容保存在列表里(每行后有换行符)

写操作:

1.write:可理解为用Pycharm向文件里写内容

2.mode 为 ’w‘ 表示写操作(会覆盖之前内容)

             为 'a' 表示在原内容下进行追加写入(不覆盖原内容)

3.每次写操作结束后需要关闭管道,stream.close()

  1. stream = open(r'D:\python\PyCharm\test1.txt','a')
  2. result = stream.writable() #判断文件的可修改性
  3. result1 = stream.write(s) #返回值是写入的字符个数
  4. stream.writelines(['德莱厄斯—SSS\n','卡特琳娜\n'])
  5. stream.close() #每次写操作结束后要关闭流,关闭之后无法写入

write()        向文件写入,参数为字符串形式。返回写入的字符格式

writable()    判断文件是否可修改,返回值是bool类型

writelines() 参数为列表,每写入一个元素就换行

为了便利,我们尽量使用with open() as 管道名:  ,来打开一个管道,用来代替 stream = open(),并且最后不用敲stream.close(),自动释放资源

###(读写操作)文件复制###

  1. with open('D:\python\PyCharm\PY.png','rb') as rstream:
  2. container = rstream.read() #读取文件内容
  3. with open(r'D:\python\PyCharm\test\PY.png','wb') as wstream:
  4. wstream.write(container) #写入
  5. print('文件复制完成!')

在使用该代码进行文件复制的时候,需要注意的是with .. as .. :  的格式,以及文件路径的正确。

os模块的使用:

os全称为operatng system ,os模块是Pycharm与文件管理操作系统进行交互的接口。

下面介绍一些

os模块的常用方法

os.getcwd()    获取当前文件夹的路径

os.mkdir()      在指定路径下,创建一个文件夹,文件夹存在时报错,没有返回值

os.rmdir()      在指定路径下,删除一个文件夹,文件夹不存在时报错,没有返回值

os.listdir()      将指定文件夹里的文件添加到列表里返回

os.remove()  删除文件

os.chdir()      切换目录

os模块下path里的方法:

os.path.join()             有两个字符串参数,用于拼接文件夹路径和文件名

os.path.dirname()      返回参数文件的目录(文件夹路径)

os.path.split()             参数为文件路径;切一刀,返回一个元组,元素分别为文件夹路径和文件名

os.path.splitext()        切一刀,返回一个元组,元素分别为文件路径和文件的扩展名

os.path.isabs()           判断参数是否为绝对路径

os.path.isdir()             判断参数是否为文件夹

os.path.isfile()            判断参数是否为文件

os.path.exists()          判断该文件或文件夹是否存在

os.path.getsize()        返回文件的字节大小

os.path.abspath(__file__)   返回当前文件的绝对路径;参数可换为其他文件的路径

##利用os模块下的方法,写一个函数,完成文件复制的功能

  1. src_path = r'D:\python\PyCharm\test'
  2. target_path = r'D:\测试(test)文件夹'
  3. def copy(src,target):
  4. if os.path.isdir(src) and os.path.isdir(target):
  5. filelist = os.listdir(src)
  6. for file in filelist:
  7. filepath = os.path.join(src,file)
  8. if os.path.isdir(filepath): #如果要复制的是一个文件夹而不是文件,则递归调用该函数
  9. copy(filepath,target)
  10. else:
  11. targetfile = os.path.join(target,file)
  12. with open(filepath,'rb') as rstream:
  13. container = rstream.read()
  14. with open(targetfile,'wb') as wstream:
  15. wstream.write(container)
  16. copy(src_path,target_path) #最终复制给目标文件的只有文件,没有文件夹

函数输入参数为文件夹路径,利用os.listdir()把文件夹下的文件名放到列表容器里,通过os.path.join()对文件夹路径和文件名进行拼接,配合文件的读写操作来完成文件的复制。

判断待复制的文件是否为文件夹,是文件夹则要递归调用该函数,最终复制给目标文件夹的只有文件。

##(低配版)图书管理系统 

  1. # 存储数据 D:\测试(test)文件夹\Test1
  2. # 用户注册
  3. def register():
  4. username = input('输入用户名:')
  5. password = input('输入密码:')
  6. repassword = input('确认输入密码:')
  7. if password == repassword:
  8. # 保存信息
  9. with open(r'D:\测试(test)文件夹\Test1\user.txt', 'a') as wstream:
  10. wstream.write('{} {}\n'.format(username, password))
  11. # wstream.writelines([username+' ',password+'\n'])
  12. print('注册成功!')
  13. else:
  14. print('两次输入密码不一致,请再次尝试注册!')
  15. register()
  16. def login():
  17. username = input('输入用户名:')
  18. password = input('输入密码:')
  19. if username and password:
  20. with open(r'D:\测试(test)文件夹\Test1\user.txt', 'r') as rstream:
  21. while True:
  22. user = rstream.readline()
  23. input_user = '{} {}\n'.format(username, password)
  24. if input_user == user:
  25. print('登录成功!')
  26. show_books()
  27. add_books()
  28. break
  29. else:
  30. print('用户名或密码错误,请重新登录!')
  31. login()
  32. def show_books():
  33. print('------图书馆里的书有------')
  34. with open(r'D:\测试(test)文件夹\Test1\books.txt', encoding="utf-8") as rstream:
  35. booklist = rstream.readlines()
  36. for book in booklist:
  37. print(book, end='')
  38. def add_books():
  39. choice = input('请选择你要借阅的书籍:')
  40. choice = choice + '\n'
  41. with open(r'D:\测试(test)文件夹\Test1\books.txt', encoding="utf-8") as rstream:
  42. booklist = rstream.readlines()
  43. print(booklist)
  44. if choice in booklist:
  45. print('借阅成功!')
  46. else:
  47. print('查无此书!')
  48. # register()
  49. # show_books()
  50. login()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/838515
推荐阅读
相关标签
  

闽ICP备14008679号