Python | file reading and writing

Data Valley 2021-01-22 11:05:16
python file reading writing


This time, Xiao Li's popular science is about the knowledge of reading and writing documents , We can also use python Read the file !

01

summary

Python The function of reading and writing files is built in The core : Reading and writing files actually requests the operating system to open a file object 【 File descriptor 】

02

Reading documents

step : a. Open file :open() b. Read file contents :read() c. Close file :close() Be careful : Remember to close the file after using it , Because file objects will occupy the system resources of the operating system , And the number of files opened by the operating system in the same period of time is limited , In order to avoid the waste of resources .

For your understanding , Let's talk about the specific parameters :

"""
open(path,flag,[encoding,errors])
path: Path to file 【 Absolute path and relative path 】
flag: How to open a file
r: read-only
rb: Open the file in binary format , read-only
r+: Reading and writing
w: Write only
wb: Write to file in binary format , If the file already exists, override , If not, create a new file
w+: Reading and writing
a:append, If something already exists in a file , The new content will be added after the original content
encoding: Coding format ,utf-8,gbk
errors: Error handling
"""

One 、 Open file

path = "C:/Users/jiejie/Desktop/ To oak .txt"
#r: Open the file as read-only
f = open(path,"r",encoding="gbk")
"""
Be careful 1: When we use r When opening a file in the form of :
If the file format is gbk Of , Can not add encoding = "gbk"
If the file format is utf-8, Must be added encoding = "utf-8"
Be careful 2: Binary format is generally used to process pictures , video , Audio
If the document is rb perhaps wb Open in the form of , Can not add encoding, Will report a mistake
encode(): code
decode(): decode
"""

Two 、 Read the file

#1. Read all ************
str = f.read()
print(str)
#2. Reads the specified number of characters
# If every line ends with a "\n" Symbol , Also known as characters
str1 = f.read(2)
print(str1)
#3. Read entire line , No matter how many characters the line has **********
# Call to read one line at a time , After reading a line , Move the cursor of the operation file to the beginning of the next line
str2 = f.readline()
print(str2)
str2 = f.readline(3) # Read... In one line 3 Characters
print(str2)
#4. Read everything out , Return a list , Each row of data is an element
result = f.readlines()
print(result)
3、 ... and 、 Close file
f.close()
Next, let's apply it briefly , Abbreviation :
path = " To oak .txt"
# Shorthand way
# benefits : You don't need to do it manually close, Avoid the waste of resources caused by forgetting to close the file
with open(path,"r",encoding="gbk") as f:
result = f.read()
print(result)
try:
f1 = open(path,"r",encoding="gbk")
print(f1.read())
except FileNotFoundError as e:
print(" file does not exist ",e)
except LookupError as e:
print(" Unknown encoding specified ")
except UnicodeDecodeError as e:
print(" Read file decode error ",e)
finally:
if f1:
f1.close()

03

Writing documents

step : a. Open file b. Write information to the cache c. Refresh file internal buffer 【 Improve the efficiency of writing 】 d. Close file Be careful : If the file to write the content doesn't exist , A file is automatically created

path = "file11.txt"
#1. Open file
f = open(path,"w",encoding="utf-8")
#2. Write content , Write the content to the buffer
f.write("Whatever is worth doing is worth doing well The bank is very proud, very critical ")
#3. Refresh buffer 【 Speed up the flow of data , Keep the buffer flowing 】
f.flush()
#4. Close file
f.close()
 Shorthand way : You don't have to call it manually close
with open(path,"w",encoding="utf-8") as f1:
f.write("Whatever is worth doing is worth doing well The bank is very proud, very critical ")

04

Encoding and decoding

String type and byte type conversion process String type to byte type : code ,encode Byte type to string type : decode ,decode

str = " Today is a good day today is a good day"
path = "C:/Users/jiejie/Desktop/file22.txt"
with open(path,"wb") as f:
result = str.encode("utf-8")
print(result)
f.write(result)
with open(path,"rb") as f1:
data = f1.read()
print(data)
print(type(data))
newData = data.decode("utf-8")
print(newData)
print(type(newData))

05

practice : Copy files

demand : Realize the copy of file content Ideas : Source file : Read it out Target file : Write to

import os
def myCopy(srcPath,desPath):
#1. Determine whether the source file exists
if not os.path.exists(srcPath):
print(" Brother , file does not exist , Don't copy it ")
return
#2. Determine whether the source file is a file type
if not os.path.isfile(srcPath):
print(" It's not a document , Cannot copy ")
return
#3. Open source and target files
srcFile = open(srcPath,"rb")
desFile = open(desPath,"wb")
#4. Get the size of the source file
size = os.path.getsize(srcPath)
while size > 0:
# Read
content = srcFile.read(1024)
# write in
desFile.write(content)
size -= 1024
#5. Close file
srcFile.close()
desFile.close()
myCopy("file11.txt","file22.txt")

summary : Above we have explained the knowledge of file reading and writing , Reading documents , Writing documents , And about the various parameters , Encoding and decoding of files , Finally, there is a copy of the contents of the file , If you are interested, you can press to operate it ! Welcome to discuss with you ~~~

1

That's all for today's sharing ~ Welcome to discuss ~~~

This article is from WeChat official account. - Data Valley (BigDataValley)

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2021-01-15

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Data Valley]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/01/20210122104349910y.html

  1. 前后端分离有什么了不起,手把手教你用Python爬下来!
  2. 在 Azure 上执行一些简单的 python 工作
  3. 推荐 :利用Python的混合集成机器学习(附链接)
  4. Cunning or orthodox Kung Fu? The most complete usage of Python derivation
  5. It's estimated that 80% of pandas people have to hang up!
  6. What's so great about the separation of front and rear ends? Hand in hand teach you to climb down with Python!
  7. Doing some simple Python work on azure
  8. Recommendation: hybrid integrated machine learning using python (link attached)
  9. Learning PPO algorithm programming from scratch (Python version)
  10. Python OpenCV 图片模糊操作 blur 与 medianBlur
  11. Python OpenCV image blur operation blur and mediablur
  12. 成功解决cv2.error: OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: err
  13. Cv2.error solved successfully: opencv (4.1.2) C:: (projects / opencv Python / opencv modules / imgproc / SRC)\ color.cpp:182 : err
  14. Python 中使用 virtualenv 管理虚拟环境
  15. Using virtualenv to manage virtual environment in Python
  16. 如何使用Python执行系统命令?Python学习教程!
  17. How to use Python to execute system commands? Python tutorial!
  18. 快速掌握Python中的循环技术
  19. Quickly grasp the loop technology in Python
  20. Python主流Web框架之Tornado
  21. appium+python自动化63-使用Uiautomator2报错问题解决
  22. Tornado: the mainstream Python Web Framework
  23. Appium + Python automation 63 - using uiautomator2 to solve the problem of error reporting
  24. 爬虫+django,打造个性化API接口
  25. Crawler + Django to create personalized API interface
  26. 爬虫+django,打造个性化API接口
  27. Crawler + Django to create personalized API interface
  28. C、C++、Java、PHP、Python主要应用在哪里方面?
  29. C. Where are the main applications of C + +, Java, PHP and python?
  30. Python 无限级分类树状结构生成算法 「实用代码」
  31. Python infinite classification tree structure generation algorithm "practical code"
  32. 【Azure 存储服务】Python模块(azure.cosmosdb.table)直接对表存储(Storage Account Table)做操作示例
  33. [azure storage service] Python module( azure.cosmosdb.table )Direct operation example of storage account table
  34. 【Azure 存储服务】Python模块(azure.cosmosdb.table)直接对表存储(Storage Account Table)做操作示例
  35. [azure storage service] Python module( azure.cosmosdb.table )Direct operation example of storage account table
  36. openpose c++ 配置教程 + python api
  37. Openpose C + + configuration tutorial + Python API
  38. PYTHON爬虫实战_垃圾佬闲鱼爬虫转转爬虫数据整合自用二手急速响应捡垃圾平台_3(附源码持续更新)
  39. 使用python javaSerializationTools模块拼接生成 8u20 Gadget
  40. 萌新入门之python基础语法
  41. python中hmac模块的使用
  42. Python crawler_ Garbage man idle fish crawler turn crawler data integration self use second hand rapid response garbage collection platform_ 3 (with continuous source update)
  43. Using Python javaserialization tools module to generate 8u20 gadget
  44. The basic syntax of Python
  45. The use of HMAC module in Python
  46. 攻防世界web进阶区Web_python_block_chain详解
  47. Attack and defense world web advanced zone Web_ python_ block_ Details of chain
  48. pandas DataFrame的新增行列,修改、删除、筛选、判断元素以及转置操作
  49. Add rows and columns, modify, delete, filter, judge elements and transpose operations in pandas dataframe
  50. pandas DataFrame的新增行列,修改、删除、筛选、判断元素以及转置操作
  51. Add rows and columns, modify, delete, filter, judge elements and transpose operations in pandas dataframe
  52. 虚言妙诀终虚见,面试躬行是致知,Python技术面试策略与技巧实战记录
  53. The interview practice is knowledge, python technology interview strategy and skills of the actual record
  54. 用tqdm和rich为固定路径和目标的python算法代码实现进度条
  55. Using tqdm and rich as the fixed path and target of Python algorithm code to realize the progress bar
  56. 我来记笔记啦-Django开发流程与配置
  57. Let me take notes - Django development process and configuration
  58. python数据类型的强制转换
  59. Django报错:'Key 'id' not found in 'xxx'. Choices are: xxx'
  60. Python400集大型视频,从正确的方向出发学习,全套完整送给大家