first, the standard input and output
1. Print to screen
The easiest way to produce output is to use the print statement, which allows you to separate 0 or more expressions with commas. This function-passing expression is converted to a string, and the following result is written to the standard output-
Print ("Python is really a great language," "isn ' t it?")
This produces the following results on the standard screen:
Python is really a great language, isn ' t it?
2. Reading keyboard input
There are two built-in functions in Python2 that can read data from standard input, which defaults from the keyboard. These functions are: input () and raw_input ().
In Python3, however, the raw_input () function has been deprecated. In addition, the input () function reads data from the keyboard as a string, regardless of whether quotation marks ("or") are used.
Example:
X=input ("Please enter x=")
y=input ("Enter y=")
z=x+y
print ("x+y=" +z)
Run Result:
Please enter x=111
Please enter y=222
x+y=111222
You can see that the return value of input is always a string, and we need to use the form int (input ()) when we need to return the int type, for example:
X=int (Input ("Please enter x="))
Y=int (Input ("Please enter y=")
z=x+y
print ("x+y=", Z)
The results of the operation are as follows:
Please enter x=111
Please enter y=222
x+y= 333
3, formatted output
In general, we want more control over the output format than simply separating it with a space. There are two ways of doing this:
The first is in your own control. Use string slices, join operations, and some useful actions that string contains.
Example:
# The first way: Control for
x in range (1, one):
print (str (x). Rjust (2), str (x*x). Rjust (3), end= ")
Output:
1 1 1 2 4 8 3 9 (4)
5 MB
6 216
7 343
8
9 bayi 729
10 100 1000
In the first approach, the Str.rjust () method of the string object is used to keep the string to the right, and by default padding the space on the left, the length is specified by the parameter, and a similar method is Str.ljust () and Str.center (). These methods do not write anything, they simply return a new string, and if the input is long, they do not truncate the string.
The second is the use of the Str.format () method.
Usage: It uses the position parameter in place of the traditional% method via {} and:
Main points: From the following examples you can see that the position parameters are not in order constraints, and can be {}, as long as there is a corresponding parameter value in the format, the parameter index from 0 open, the incoming location parameter list available in the form of * list.
>>> li = [' HoHo ', []
>>> ' My name is {}, age {} '. Format (' HoHo ',? ')
' My name is HoHo, age '
>>> ' My name was {1}, age {0} '. Format ("HoHo ') ' My
name is HoHo, age '
>>> '" My name is {1}, Age {0} {1} '. Format ("HoHo ') ' My
name is HoHo, age HoHo '
>>> ' I name is {}, age {} '. Format (*li)
' My name was HoHo, age 18 '
Working with keyword parameters
IMPORTANT: Keyword parameter values to be right, available in the dictionary when the keyword parameter passed the value, the dictionary plus * * can be
>>> hash = {' name ': ' HoHo ', ' Age ': [}
>>> ' My name is {name},age.} '. Format (name= ' HoHo ', age= ' My
name is Hoho,age ' >>> ' I name is ' {name},age ' ' ' ' ', ' is ' {# '
O,age is 18 '
padding and formatting
Format: {0:[padding character] [alignment <^>][width]}.format ()
>>> ' {0:*>10} '. Format # #右对齐
' ********20 '
>>> ' {0:*<10} '. Format # #左对齐
' 20******** '
>>> ' {0:*^10} '. Format # #居中对齐
' ****20**** '
Precision and system
>>> ' {0:.2f} '. Format (1/3)
' 0.33 '
>>> ' {0:b} '. Format #二进制
' 1010 '
>>> ' {0:o} '. Format #八进制
' '
>>> ' {0:x} '. Format #16进制
' a '
>>> ' {:,} '. Format (12369132698) #千分位格式化
' 12,369,132,698 '
Using indexes
>>> Li
[' HoHo ',]
>>> ' name is {0[0]} ' the ' is {0[1]} '. Format (LI)
' name was HoHo age is 18
Second, file IO
Python provides the basic functionality and the necessary default action file method. Use a file object to do most of the file operations. 1, open function
Before reading or writing a file, you must use the Python built-in open () function to open it. This function creates a file object that will be used to invoke other support methods associated with it.
Grammar:
File Object = open (file_name [, access_mode][, Buffering])
The following are the details of the parameters:
file_name: The filename (file_name) parameter is a string value that contains the file name you want to access.
ACCESS_MODE:ACCESS_MODE specifies that the file has been opened, that is, read, write, append, and so on. A complete list of possible values, as shown in the table below. This is an optional parameter, and the default file access mode is read (R).
Buffering: If the buffer value is set to 0, the buffer is not used. If the buffer value is 1, a buffer is made when a file is accessed. If you specify an integer that has a buffer value greater than 1, the buffer is buffered using the indicated buffer size. If this is a negative number, the buffer size is the default behavior of the system.
Typically, the file is opened as text, which means that the string you read out of the file and write to the file is encoded in a particular encoding (by default, UTF-8).
You can append the parameter ' B ' to the mode to open the file in binary mode: The data is read out and written as a byte object. This pattern should be used for all files that do not contain text. In text mode, the default is to convert the platform-related line terminator (on UNIX, Windows \ r \ n) to \ n. When written in text mode, the default is to convert the occurrence of \ n to a platform-related line terminator. This covert modification has no problem with ASCII text files, but it can damage data in binary files such as JPEG or EXE. Be especially careful when reading and writing to this type of file in binary mode. 2, File object Properties
Once the file is opened, there will be a file object, and you can get a variety of information about the file.
File.closed: False if the file is closed returns True
File.mode: Return File open access mode
File.name: Return file name
Test:
# Open a file
fo = open ("Foo.txt", "WB")
print ("Name of the file:", Fo.name)
print ("Closed or Not:", fo.c losed)
print ("Opening mode:", Fo.mode)
fo.close ()
print ("Closed or Not:", fo.closed)
Run Result:
Name of the file: foo.txt
Closed or not: False
Opening mode: WB
Closed or not: True
3, the method of the file object
Suppose you have created a file object called F. F.read ()
To read the contents of a file, call F.read (size), which reads a certain number of data and returns as a string or byte object.
The size is an optional parameter for the numeric type. When size is ignored or negative, all the contents of the file are read and returned.
The following example assumes that the file Foo.txt already exists and that the contents are as follows:
Hello World.
Hello Python.
The code is as follows:
# Opens a file
f = open ("Foo.txt", "R", encoding= ' UTF-8 ')
str = f.read ()
print (str)
# Close Open File
F.close ()
Execute the above procedure, the output result is:
Hello World.
Hello Python.
F.readline ()
F.readline () reads a separate row from the file. The line feed is ' \ n '. F.readline () If an empty string is returned, it indicates that the last row has already been read.
# Opens a file
f = open ("Foo.txt", "R", encoding= ' UTF-8 ')
str = f.readline ()
print (str)
# Close Open File
F.close ()
Execute the above procedure, the output result is:
Hello World.
F.readlines ()
F.readlines () returns all the rows contained in the file.
If the optional parameter sizehint is set, the bytes of the specified length are read and the bytes are split by row.
# Opens a file
f = open ("Foo.txt", "R", encoding= ' UTF-8 ')
str = f.readlines ()
print (str)
# Close Open File
F.close ()
Execute the above procedure, the output result is:
[' Hello World '. \ n ', ' Hello Python. ']
Another way is to iterate over a file object and then read each row:
# Opens a file
f = open ("Foo.txt", "R", encoding= "UTF-8") for line
in F:
print (line, end= ")
# Close Open File
F.close ()
Execute the above procedure, the output result is:
Hello World.
Hello Python.
This method is simple, but does not provide a good control. Because the processing mechanism of the two is different, it is best not to mix. F.write ()
F.write (String) writes a string to a file, and then returns the number of characters written.
# Open a file
f = open ("Foo.txt", "W", encoding= "UTF-8")
num = F.write ("Python is a very good language.") Yes, very good indeed!! \ n ")
print (num)
# closes open file
f.close ()
Execute the above procedure, the output result is:
29
Open foo.txt its contents are as follows:
Python is a very good language.
yes, very good indeed!!
If you want to write something that is not a string, you will need to convert it first:
# Opens a file
f = open ("Foo.txt", "W", encoding= "UTF-8")
value = (' www.baidu.com ', 666)
s = str (value)
F.write (s)
# Close Open file
f.close ()
To execute the above program, open the Foo.txt file:
(' www.baidu.com ', 666)
F.tell ()
F.tell () returns the current position of the file object, which is the number of bytes from the beginning of the file. F.seek ()
If you want to change the current location of the file, you can use the F.seek (offset, from_what) function.
From_what value, if 0 is the beginning, if 1 represents the current position, 2 indicates the end of the file, for example:
Seek (x,0): Moves x characters from the start position, the beginning of the file first-line character
Seek (x,1): means to move x characters from the current position
Seek (-x,2): means to move x characters forward from the end of a file
The From_what value defaults to 0, which is the beginning of the file. A complete example is given below:
>>> f = open (' Foo.txt ', ' rb+ ')
>>> f.write (b ' 0123456789abcdef ')
>>> F.seek (5) # Move to the sixth byte of the file
5
>>> f.read (1)
B ' 5 '
>>> F.seek (-3, 2) # move to the last third byte
of the file >>> f.read (1)
B ' d '
In a text file (those that do not have B in the mode that opens the file), the location is only relative to the start of the file.
When you have finished processing a file, call F.close () to close the file and free the system's resources, and if you try to call the file again, an exception is thrown.
>>> f.close ()
>>> f.read ()
Traceback (most recent call last):
File ' <stdin> ', line 1, in?
VALUEERROR:I/O operation on closed file
Using the WITH keyword is a great way to work with a file object. At the end, it will help you to properly close the file. It is also written to be shorter than the try-finally statement block:
>>> with open ('/tmp/foo.txt ', ' R ') as F:
... Read_data = F.read ()
>>> f.closed
True
4. Using JSON to store structured data
It is easy to read and write strings from a file. The value is going to be a little bit more complicated because the read () method returns a string and passes it in a function such as int () to convert a string of ' 123 ' to the corresponding value 123. When you want to save more complex data types, such as nested lists and dictionaries, it becomes more complex to manually parse and serialize them.
Python allows you to use the commonly used Data Interchange Format JSON (JavaScript Object notation). Standard module JSON can accept Python data structures and convert them to string representations, a process called serialization. Rebuilding a data structure from a string representation is called deserialization. In the process of serialization and deserialization, the string representing the object can be stored in either the file or the data, or transmitted to the remote machine over a network connection.
If you have an object x, you can view its JSON string representation in a simple line of code:
>>> Json.dumps ([1, ' Simple ', ' list '])
' [1, ' Simple ', ' list '] '
Another variant of the dumps () function, dump (), serializes the object directly into a file. So if f is a file object that is opened for writing, we can do this:
Json.dump (x, F)
To decode an object, you can use:
x = Json.load (f)
Let's write a short program that stores a set of numbers, and then write a program that reads the numbers into memory, the first program uses Json.dump () to store the numbers, and the second program uses Json.load ()
The function Json.dump () accepts two arguments: the data to be stored and the file objects that can be used to store the data. Here is a demo example
Import JSON number
= [1,2,3,5]
file_name = ' Number.json ' #通过扩展名指纹文件存储的数据为json格式
with open (file_name, ' W ') As File_object:
json.dump (Number,file_object)
We first import the JSON module, and then create a list of numbers that we specify to store in Number.json, where the file suffix is. JSON to indicate that the file is stored in JSON format, and we open the file in write mode so that JSON can see the data written to it using Json.dump () Write the data, we do not write output statements, open the file view, the data stored in the same format as Python.
Note the Json.dump () method, passing two arguments the first data to be written, and the second file object for the location to store. Example Two
Write a program to read in memory using Json.load ()
Import JSON
file_name = ' Number.json ' #通过扩展名指纹文件存储的数据为json格式
with open (file_name, ' R ') as File_object:
Contents = Json.load (file_object)
print (contents)
This is a simple way to share data between programs save and read user-generated data
For data entered by the user, saving with JSON is helpful, because if you do not store it in some way, the user's information will be lost when the program stops running. Look at an example
When the user first runs the program is prompted to enter his own name, run the program again to remember him, we first save the name
IPT = input (' Enter your name ')
filename1 = ' Name.json '
with open (filename1, ' W ') as File_object:
json.dump ( IPT, File_object)
Re-read previously stored names
With open (filename1, ' R ') as File_object:
name_ipt = Json.load (file_object)
print (' wleccome%s '%name_ipt)
We combine these two programs into one, in the execution of the time first go to Name.json try to get user name, if not this file, with Try-except handle this error, merged into the user input name and save to Name.json
Import JSON
filename1 = ' Name.json '
try: With
open (filename1) as File_object:
username = json.load ( File_object)
except Filenotfounderror:
with open (filename1, ' W ') as File_object2:
user_ipt = input (' Enter Your name I'll rember you: ')
json.dump (user_ipt,file_object2)
else:
print (username)
three, the common method of OS module
Python's OS modules provide a way to perform file processing operations, such as renaming and deleting files. To use this module, you need to import it first, and then you can invoke any related functionality. 1. Renaming and deleting files rename () method
The rename () method has two parameters, the current file name, and the new file name.
Os.rename (Current_file_name, New_file_name)
Example
The following example is used to rename an existing file Test1.txt to Test2.txt:
#!/usr/bin/python3
import os
# Rename a file from Test1.txt to Test2.txt
os.rename ("Test1.txt", " Test2.txt ")
Remove () method
You can use the Remove () method to delete a file by providing a parameter file name (file_name).
Os.remove (file_name)
Example
Here is an example of deleting an existing file Test2.txt-
#!/usr/bin/python3
import os
# Delete file test2.txt
os.remove ("Text2.txt")
2. Python directory
All files contain different directories, and Python does not have any problems with these directory operations. There are several ways to create, delete, and change directories in the OS module. mkdir () method
You can use the mkdir () method in the OS module to create a directory under the current directory. You need to provide a parameter to this method to specify the name of the directory to create.
Os.mkdir ("Newdir")
Example
The following is an example of creating a test directory in the current directory-
#!/usr/bin/python3
import os
# Create a directory "test"
os.mkdir ("test")
ChDir () method
You can use the ChDir () method to change the current directory. The ChDir () method accepts a parameter, which is the directory name of the directory you want to create in the current directory.
Os.chdir ("Newdir")
Example
Here's an example of entering the "/home/newdir" directory-
#!/usr/bin/python3
import os
# Changing a directory to "/home/newdir"
os.chdir ("/home/newdir")
GETCWD () method
The GETCWD () method displays the current working directory.
OS.GETCWD ()
Example
Here is an example of getting the current directory-
#!/usr/bin/python3
import OS
# This would give location to the current directory
OS.GETCWD ()
RmDir () method
The RmDir () method deletes the directory, which is passed as a parameter to the method.
Before you delete a directory, all of its contents should be deleted first.
Os.rmdir (' dirname ')
Example
The following is an example of deleting the "/tmp/test" directory. It requires a fully qualified name for the given directory, otherwise the directory is searched from the current directory.
#!/usr/bin/python3
import OS
# This would remove "/tmp/test" directory.
Os.rmdir ("/tmp/test" )