Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of File Operation and exception handling in python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the example analysis of file operation and exception handling in python, which is very detailed and has a certain reference value. Interested friends must read it!

I. Operation of the file 1.1 create the file

Format: F = open ('file','w') or f = open ('file','r')

1.2 write data

Format: F = open ('file','w') or f = open ('file','r')

1.3 read data

Object = open ("file", r)

Variable = object .read ()

Print (variable)

If you open a file with open, if you use "r", you can omit it, that is, only write open ('test.txt') if there is no file, open an error, and the file can operate. If there is a Chinese display in the file, there will be garbled codes that need to be added to encoding='utf-8' open (' test.txt', "r", encoding='utf-8').

1.4 2 read data

Object = open ("file", r)

Variable = object .readlines ()

Print (variable)

1.5 read and write data

Object = open ("binary", rb)

Variable = object .read ()

Print (variable)

1.6 Delete files

1.7 write to a file

1.8 read pictures

1.9 back up pictures

With open ("binary", "wb") as object:

Variable = object .write ()

Print (variable)

1.10 File renaming

Import os

Os.rename ("File name to be modified", "New File name")

1.11 create a folder

1.11 get the current directory

II. Exception 2.1 demonstration of all kinds of anomalies

2.2 catch exception

2.3try/finally

2.4 Transmission of exceptions

2.5 trigger exception

2.6 Custom exception

The above is all the contents of the article "sample Analysis of File manipulation and exception handling in python". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report