Get the App
SLTechnology News&Howtos  ›  Development  › 

How to read and write python files

Shulou Source: shulou.com Published: 2022-05-31 17:43:51 10月30日 Update

This article mainly introduces the python file how to read and write the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this python file how to read and write the article will have a harvest, let's take a look.

1. Read, the read () method returns the string saved in the file.

The readlines () method, which gets a list of strings from the file. Each string in the list is each line in the text.

> helloContent = file.read () > helloContent'Hello worldview'

2. Write, pass w as the second parameter to open (), open the file in writing mode, and you can write the content to the file by write ().

W mode deletes the original contents of the file and rewrites it.

If you do not want to delete the original content, you can add the content to the file in a mode.

> baconFile = open ('bacon.txt', 'w') > baconFile.write (' Hello world!\ n') 13 > > baconFile.close () > baconFile = open ('bacon.txt',' a') > baconFile.write ('Bacon is not a vegetable.') 25 > baconFile.close () > baconFile = open (' bacon.txt') > content = baconFile.read () > > baconFile.close () > > print (content) Hello worldstanding Bacon is not a vegetable. This is the end of the article on "how to read and write python files". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to read and write python files". If you want to learn more, you are welcome to follow the industry information channel.

Tags: File content character string pattern knowledge primitive can be passed through method article line value parameter easy to operate text article way easy to understand more see Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Microsoft Apple Huawei Redmi