Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the handling of file operations and exceptions in python

Shulou Source: shulou.com Published: 2022-06-02 05:21:11 09月10日 Update

This article shows you how to handle file operations and exceptions in python. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

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.6 write to a file

1.7 read pictures

1.8 back up pictures

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

Variable = object .write ()

Print (variable)

1.9 File renaming

Import os

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

1.10 create a folder

1.11 get the current directory

1.12 read and write binaries

Know how to read and write text files to read and write binary files is also very simple, the following code to achieve the function of copying picture files.

Def main (): try: with open ('guido.jpg',' rb') as fs1: data = fs1.read () print (type (data)) # with open ('Guido. Jpg', 'wb') as fs2: fs2.write (data) except FileNotFoundError as e: print (' specified file cannot be opened.') Except IOError as e: print ('error reading and writing file') Print ('end of program execution.') if _ _ name__ = ='_ main__': main () 2.1.Demo of all kinds of exceptions

2.2 catch exception

2.3try/finally

2.4 Transmission of exceptions

2.5 trigger exception

2.6 Custom exception

The above is what the file manipulation and exception handling is like in python. Have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: File variable object binary data picture processing content skill file name format knowledge concise concise random code code function backup that is folder Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS MySQL MariaDB Linux OPPO Reno