Output format:
python has two ways to output values: expression statement and print() function.
The third way is to use the write() method of the file object. The standard output file can use sys Stdout reference.
The str.format() function formats the output value.
repr() and str() can convert the output value into a string (str(): the function returns a user-friendly expression.
repr(): produces an interpreter readable expression)
1.TEST repr() & str()
#!/usr/bin/python3 str1 = 'hello' print('str1:',str1) print('repr(str1):',repr(str1),',type(repr(str1)):',type(repr(str1))) print('str(str1):',str(str1),',type(str(str1)):',type(str(str1))) print('str(1/7):',str(1/7)) x = 10 * 15 y = 12 * 3.15 #+The number is used to splice strings s = 'x The value of is:'+ repr(x) + ', y The value of is: ' + repr(y) +'...' print(s,type(s)) s1 = 'x The value of is:', repr(x) ,', y The value of is: ' , repr(y) ,'...' print(s1,type(s1)) #The repr() function can transfer special characters in a string str2 = 'hello ,Vegetable chicken\n' print('str2:',str2) print('repr(str2):',repr(str2)) #The parameters of repr() can be any python object print(repr((12,x,y))) print(repr((x,y)))
2. TEST rjust() & zfill()
rjust(): you can move the string to the right and fill in spaces on the left.
ljust(): you can keep the string to the left and fill in spaces to the right.
zfill(): fill 0 to the left of the number
#!/usr/bin/python3 x = 1 for x in range(1,11): #Here, end = indicates that there is a splice after the result is generated. If there is no subsequent splice, the front and rear results will be spliced into one line #rjust(4) indicates that the value of four digits is less than four digits, and a space is added to the right print(repr(x).rjust(2),repr(x*x).rjust(3),end=' ') # Note the use of the previous line 'end' # print(repr(x*x*x).rjust(4)) print(repr(x*x*x).rjust(4),end=' ') print('-'.rjust(5)) #ljust usage for x in range(1,11): print(repr(x).ljust(2),repr(x*x).ljust(3),repr(x*x*x).ljust(4)) #zfill() usage, which populates the left side of the string with 0 for x in range(1,11): print(repr(x).zfill(5),repr(x*x).zfill(5),end=' ') print(repr(x*x*x).zfill(5))
3.str.format()
#!/usr/bin/python import math #str.format() str1 = 'Vegetable chicken' str2 = 'study hard' #Here, the result feedback will be different if the single quotation marks and double quotation marks are used differently print('You are now{},therefore"{}!"'.format(str1,str2)) #format print('{1}{0}'.format(str1,str2)) print('{0}{1}'.format(str1,str2)) #If keyword parameters are used in format(), their values also point to the parameter with that name print('You are now{name},If you don't find a way{justdo},Always{name}'.format(name='Vegetable chicken',justdo='Crowned with a peak')) #Location and keyword parameter format (error may also be reported if the location parameter is written incorrectly) print('If you want to leave{0},{justdo},At least{1}'.format(str1,str2,justdo='Crowned with a peak')) #print('If you want to leave {0},{justdo}, at least {1}'.format(justdo =' peak ', STR1, STR2)) < -- justdo will be considered to belong to position 0 and an error will be reported #! A (using ascii()),!s uses st r() and! R (using repr()) can be used to convert a value before formatting it) print('constant PI The approximate value of is:{}'.format(math.pi)) print('constant PI The approximate value of is:{!r}. '.format(math.pi)) print('constant PI Value of:{!a}'.format(math.pi)) #Optional: and format identifiers can be followed by field names. This allows better formatting of values. print('constant PI The approximate value of is{0:.3f}. '.format(math.pi)) #Pass in an integer after: to ensure that the field has at least so much width. Useful when users beautify tables: table = {'google':1,'Tencent':2,'Taobao':3} print(table) for name,number in table.items(): print('{0:10}==>{1:10d}'.format(name,number)) #If you have a long format string and you don't want to separate them, it's good to format by variable name instead of position. #The simplest is to pass in a dictionary and use square brackets [] to access the key value table = {'google':1,'Tencent':2,'Taobao':3} print('Tencent:{0[Tencent]:d};google:{0[google]:d};Taobao:{0[Taobao]:d}'.format(table)) table = {'google':11,'Tencent':22,'Taobao':33} print('Tencent:{0[Tencent]:d};google:{0[google]:d};Taobao:{0[Taobao]:d}'.format(table)) #You can also use * * in front of the table variable to achieve the same function: table = {'google':1,'Tencent':2,'Taobao':3} print('Tencent:{Tencent:d};google:{google:d};Taobao:{Taobao:d}'.format(**table))
4. Old style string formatting
%Operators can implement string formatting. It takes the parameters on the left as a format string similar to sprintf(), substitutes the parameters on the right, and then returns the formatted string.
#!/usr/bin/python3 import math print('pi:',math.pi) print('pi Keep three decimal places:%5.3f.' %math.pi)
5. Read keyboard input
#!/usr/bin/python str = input('text what u want to say:') print(str)
6. Reading and writing documents
open() will return a file object. The basic syntax format is as follows:
open(filename,mode) #filename: a string value containing the name of the file to be accessed #Mode: determines the mode of opening the file: read-only, write, append, etc. This parameter is optional. The default file access mode is read-only (r)
The values of the open(filename,mode)mode part are as follows:
MODE | describe |
r | Open the file as read-only. The pointer to the file will be placed at the beginning of the file. (default mode) |
rb | Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. |
r+ | Open a file for reading and writing. The file pointer will be placed at the beginning of the file. |
rb+ | Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. |
w | Open a file for writing only. If the file already exists and is edited from the beginning, the original content will be deleted. If it does not exist, a new file is created. |
wb | Open a file in binary format for writing only. If the file already exists and is edited from the beginning, the original content will be deleted. If the file does not exist, create a new file. |
w+ | Open a file for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. |
wb+ | Open a file in binary format for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If not, create a new file. |
a | Open a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing. |
ab | Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing. |
a+ | Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. Append mode is enabled when the file is opened. If the file does not exist, create a file for reading and writing |
ab+ | Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing. |
mode | r | r+ | w | w+ | a | a+ |
read | + | + | + | + | ||
write | + | + | + | + | + | |
establish | + | + | + | + | ||
cover | + | + | ||||
Pointer at the beginning | + | + | + | + | ||
Pointer at end | + | + |
#!/usr/bin/python3 #Open a file f = open(file="D:\work\Python Instance location\\20210609_test_file.txt",mode="w") ''' file The parameter is the file name to open. mode Parameter describes the characters used by the file. mode Can be'r'If the file is read-only,'w'Write only(If a file with the same name exists, it will be deleted),and'a'Used to add file content; Any data written will be automatically added to the end of the.'r+'It is also used for reading and writing. mode Parameter is optional;'r'Will be the default. ''' f.write("You don't think you can be a local tyrant.\n It turned out!\n") f.close()
7. Method of document object
7.1f.read()
To read the contents of a file, call f.read(size), which reads a certain amount of data and returns it as a string or byte object.
Size is an optional numeric parameter. When size is ignored or negative, all the contents of the file will be read and returned.
#!/usr/bin/python3 #Open yesterday's file f = open(file="D:\work\Python Instance location\\20210609_test_file.txt",mode="r") str = f.read() print(str) #Close open files f.close()
7.2 f.readline()
f.readline() reads a single line from the file. The newline character is' \ n '.
f. If readline() returns an empty string, it indicates that the last line has been read.
#!/usr/bin/python3 f = open("D:\work\Python Instance location\\20210609_test_file.txt","r") str = f.readline() print(str) f.close
7.3 f.readlines()
f.readlines() will return all the lines contained in the file.
If the optional parameter sizehint is set, bytes of the specified length are read and divided into rows.
#!/usr/bin/python3 f = open("D:\work\Python Instance location\\20210609_test_file.txt","r") str = f.readlines() print(str) f.close
7.4 f.write()
f.write(string) writes string to a file, and then returns the number of characters written.
#!/usr/bin/python3 f = open("D:\work\Python Instance location\\20210609_test_file.txt",mode="w") num = f.write('123456') print(num) f.close()
7.5 f.tell()
f.tell() returns the current location of the file object, which is the number of bytes from the beginning of file penetration
#!/usr/bin/python3 f = open("D:\work\Python Instance location\\20210609_test_file.txt",mode="w") num = f.write('123456') k = f.tell() print(num) print('k',=k) f.close()
7.6 f.seek()
If you want to change the current location of the file, you can use the f.seek(offset,from_what) function.
from_ The value of what. If it is 0, it means the beginning, if it is 1, it means the current location, and 2 means the end of the file.
- seek(x,0): it means to move x characters from the starting position, that is, the first line of the file;
- seek(x,1): move x characters backward from the current position;
- seek(-x,2): move x characters forward from the end of the file;
#!/usr/bin/python3 f = open("D:\work\Python Instance location\\20210616_test_file.txt",'wb+') #Write in b bytes f.write(b'0123456abcde') l1 = f.seek(5) print(l1) r = f.read(1) print(r) #Move to the third byte of the file l2 = f.seek(-3,2) print(l2) f.close() print('-------------------------') f = open("D:\work\Python Instance location\\20210616_test_file2.txt",'w+') f.write('China will certainly regain its historical status, which is the responsibility entrusted to China by history') print(f.tell()) #The pull position is 0 print(f.seek(0)) print(f.read()) #After reading, the pointer position will change to the end print(f.read()) print('Second reading') #Move pointer to position head s = f.seek(0) #print(s) #print(f.seek(12)) print(f.read()) #Move the pointer again #The test doesn't seem to work with strings, binary lines #f.seek(-10,2) #f.read(0) f.seek(8) print(f.read()) f.close()
7.7 f.close()
In text files (those that do not have b in the open file mode), only the starting position of the file will be located.
When you finish processing a file, call f.close() to close the file and release the system resources. If you try to call the file again, you will run out of exception.
When adding [f.read()] to the code of 7.6, the following error will appear
When dealing with a file object, using the with keyword is a very good way. At the end, it will help you close the file correctly. It is also shorter than the try -finall statement:
#!/usr/bin/python3 with open("D:\work\Python Instance location\\20210616_test_file2.txt",'r') as f: #All data is read out by cycle while True: read_data = f.read() print(read_data) if not read_data: break f.close()
7.8 pickle module
- The pickle module of python implements the basic data sequence and deserialization.
- Through the serialization operation of pickle module, we can save the object information running in the program to a file for permanent storage.
- Through the deserialization operation of the pickle module, we can create the object of the last program error from the file.
Basic interface:
pickle.dump(obj,file,[,protocol])
With the pickle object, you can open the file in the form of reading:
x = pickle.load(file) #Read a string from file and refactor it into the original python object. file:Class file object, with read()and readline()Interface.
#!/usr/bin/python3 import pickle data1 = {'a':[1,2.0,3,4+6j], 'b':('string',u'Unicode string'), 'c':None} print(data1) selfre_list = [1 ,2 ,3] selfre_list.append(selfre_list) print(selfre_list) output = open('D:\work\Python Instance location\\20210708_data.pkl','wb') print(output) pickle.dump(data1,output) pickle.dump(selfre_list,output,-1) output.close()