current position:Home>Write file operation of Python Foundation

Write file operation of Python Foundation

2022-07-26 01:42:36jiankang66

About bloggers : Former Internet manufacturer tencent staff , Network security giant Venustech staff , Alibaba cloud development community expert blogger , WeChat official account java Quality creators of basic notes ,csdn High quality creative bloggers , Entrepreneur , Knowledge sharers , Welcome to your attention , give the thumbs-up , Collection .


One 、 background

  Python Is an easy to learn 、 Powerful programming language . It provides an efficient high-level data structure , It's also a simple and effective way of object-oriented programming .Python Elegant grammar and dynamic typing and the essence of interpretive language , Make it an ideal language for scripting and rapid application development on most platforms . Now let's introduce python Knowledge of writing documents .


Two 、 Writing documents

1.write() Method

   If you open a file , File opening mode with “b”, When writing the contents of the file ,str( Parameters ) Use encode Method to byte stream , Otherwise, the report will be wrong .

file.write('Interface options'.encode())

  write() Method is used to write the specified string to a file , The syntax is as follows :

 File object name .write(str)

   example : To file “testfile.txt” Write the following data in the file .

Interface options
Generic options
Miscellaneous options
Options you shouldn’t use

file = open('testfile.txt','w')
# Enter the string... Into the file 
file.write('Interface options\n')
file.write('Generic options\n')
file.write('Miscellaneous options\n')
file.write('Options you shouldn’t use\n')
file.close()		

   give the result as follows .
 Insert picture description here

2.writelines() Method

  writelines() Method is used to write a sequence of strings to a file . This sequence of strings can be generated by an iterative object , Like a list of strings , The syntax is as follows :

 File object name .writelines(sequence)

   example : Use writelines() Method to existing “testfile.txt” The following data is added to the file .

ls = ['Environment\n','variables']	
with open('testfile.txt','a') as file:	
    file.writelines(ls)		# Append a list of strings to the file 

   give the result as follows .

 Insert picture description here


3、 ... and 、 Reference resources

1、 Liao Xuefeng's official website
2、python Official website
3、Python Programming case tutorial


Four 、 summary

   The above is about Python Knowledge of writing documents , You can refer to it , If you think it's good , Welcome to thumb up 、 Collection 、 Looking at , Welcome to wechat search java Basic notes , Relevant knowledge will be continuously updated later , Make progress together .

copyright notice
author[jiankang66],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/207/202207260138522611.html

Random recommended