Python functions and file operations

In this article, let's talk about functions and files. Function plays a very important role in programming. We can combine several statements to form a function. It can accept incoming parameters and generate output after internal related calculation. Encapsulating statements into functions is to avoid code redundancy caused by repeated use of several statements and make the code more concise and observable.

File operation mainly introduces some methods of reading and writing files, as well as the differences and matters needing attention of each method. Finally, it will introduce the way of using pickle module to store complex data.


The function mainly includes two aspects:

• built in functions

• custom functions

Built in functions are some of python's built-in functions. We can call them only by passing in relevant parameters. print is the most basic and typical built-in function; The custom function requires us to encapsulate several statements to form a new function according to our needs.

Custom function

1. Create function

The following describes some attribute words by customizing a function for calculating the volume of a box:

In [1]: def  vol(length,width,height):
   ...:     volume = length*width*height
   ...:     return volume

In the above three lines of code, you need to know:

• def: defines the keyword of the function

• length,width,height: formal parameters of the function

• return: the return value of the function

2. Call function

After creating a user-defined function, you can call the function by function name (argument):

In [2]: vol(2,2,3)
Out[2]: 12

When passing in parameters, it should be noted that the actual parameters and formal parameters must correspond exactly, such as location, number, etc., otherwise an error will be reported.

In [4]: vol(2,2)
TypeError: vol() missing 1 required positional argument: 'height'

If you want to change the parameter transfer order, you need to specify which formal parameter to transfer values for:

In [8]: vol(width=3,length=4,height=5)
Out[8]: 60

3. Function default value

The formal parameter of the function can also specify the default value. If we set the default value of the height parameter in the vol function above to 2:

In [6]: def  vol(length,width,height=2):
   ...:     volume = length*width*height
   ...:     return volume
In [7]: vol(2,2)
Out[7]: 8

At this time, only two arguments are passed into the vol function. It can be found that there is no error, and the return value is 8. That is, if a formal parameter has a default value and no value is passed for the formal parameter when calling the function, the parameter will take the default value.

4. Collection function (variable function)

We can also set the formal parameters of a function to be changeable:

In [9]: def test(*params):
   ...:     print('The length of the parameter is%d'%len(params))
   ...:     print('The third parameter is%s'%params[2])
In [10]: test(1,2,'mao',3.14,'pp')
The length of the parameter is 5
 The third parameter is mao

Here, you need to identify the formal parameters with * and then pass in several arguments when calling parameters.

5. Global and local

Constants defined in a function are called local variables, that is, they can only be called in this function and are not allowed to be used outside the function:

In [12]: def test(a,b):
    ...:     c = 2
    ...:     return a*b*c
In [13]: test(2,2)
Out[13]: 8
In [14]: print(c)
NameError: name 'c' is not defined

6. Anonymous function lambda

If the internal statements of a function are not very complex and the amount of code is small, we can use anonymous functions, such as the above function for calculating volume:

In [20]: vol = lambda a,b,c:a*b*c

In [21]: vol(2,2,3)
Out[21]: 12

lambda expressions are often nested statements. It is easy to use them in combination with related functions. Examples will be given later.

7. Embedded function

Several function nesting is also supported when defining functions, but attention should be paid to the logical relationship when using:

In [24]: def fun1(a):
    ...:     b = 2
    ...:     def fun2():
    ...:         return a*b
    ...:     return fun2()

In [25]: fun1(4)
Out[25]: 8

Common built-in functions

Built in functions have been covered in the first two articles, such as len, sorted, reversed, sum, etc. in addition, several basic built-in functions are introduced.

1.max and min

Find the maximum and minimum values in a sequence:
In [28]: min(1,2,3)
Out[28]: 1

In [29]: max(1,2,3)
Out[29]: 3


Find the absolute value of a number:

In [31]: abs(-1)
Out[31]: 1


Round to several decimal places:

In [32]: round(3.555,2)
Out[32]: 3.56


Calculate the power of a number or take the remainder:

In [33]: pow(2,3)#2*2*2
Out[33]: 8

In [34]: pow(2,3,3)#(2*2*2)%3
Out[34]: 2


Calculate the quotient and remainder of a number:

In [36]: divmod(10,3)
Out[36]: (3, 1)

Help document for querying a function:

In [37]: help(abs)
Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.


The filter() function receives two parameters. The first parameter can be a function or None, and the second parameter is a sequence. The function is to judge each element and return True or False. filter() automatically filters out the elements in the sequence that are False according to the judgment results, leaving the elements that are True. It can be used in combination with lambda expressions:

In [38]: list(filter(lambda x:x%2,range(10)))
Out[38]: [1, 3, 5, 7, 9]

The map() function takes two parameters, one is a function and the other is a sequence. The function is used to apply the function to each element in the sequence. It can also be used in combination with lambda expression:

In [42]: list(map(lambda x: x*2,range(10)))
Out[42]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]


For file reading and writing operations, the open() function must be encountered. If the file already exists, the file will be opened. If it does not exist, a file will be created. The usual usage requires two parameters: open(filename,mode).

The first parameter is the file name. The second parameter specifies how the file will be used. The following optional modes are commonly used:

• 'r': open the file as read-only (default)

• 'w': opening a file in write mode will overwrite the existing file

• 'a': open the file in write mode. If the file exists, append write at the end

• 'b': open the file in binary mode, and then there will be a combination of rb, wb and other modes method

The read() method can pass in a parameter size, that is, the length of the read content. Size is an optional parameter. If you do not pass in or pass in a negative number, all the contents of the file will be read:

In [52]: fb = open('E:/Python Basics/test.txt','r')

In [53]:
Out[53]: 'nai\nniatan'

In [54]:
Out[54]: 'g\nnaitangmao'

In [55]:
Out[55]: ''

There are three points to note:

• 1. The newline in the original file is represented by the newline '\ n' when reading, and also occupies a unit length

• 2. The content that has been read cannot be read repeatedly

• 3. If the read content returns an empty string, it indicates that the end of the file has been reached

2.readline() method

The readline() method reads a single line from the file, and there will be a newline '\ n' at the end of this line of data. If there is no data in one line, only one '\ n' will be returned. Similarly, when an empty string is returned, it indicates that the end of the file is reached.

In [59]: fb1 = open('E:/Python Basics/test.txt','r')

In [60]: fb1.readline()
Out[60]: 'nai\n'

3.readlines() method

The readlines() method is also used to read all files. The difference from read() is that the former reads by line, and finally returns a list. Each line of data is used as a list element:

In [72]: fb3 = open('E:/Python Basics/test.txt','r')

In [73]: fb3.readlines()
Out[73]: ['nai\n', 'niatang\n', 'naitangmao']

4. Traversing file object reading

The content read out in this way looks more standardized:

In [81]: for i in fb4:
    ...:     print(i,end = '')

5. File writing

There are two points we should pay attention to when writing:

• if the written data is non string content, it needs to be converted to string

• pay attention to whether to overwrite or append the writing method

In [85]: fb5 = open('E:/Python Basics/test1.txt','w')

In [89]: list1 = [1,2]
In [91]: fb5.write(str(list1))
Out[91]: 6

After writing with write, the length of the written string will be returned.

6. File closing

Remember, remember! If you open a file with open(), be sure to close the file with the close() method after the operation is completed.

In [92]: fb5.close()

7.with mode

If you feel you have a bad memory and always forget to close the file with the close() method, you should get used to using with to deal with file objects. It can automatically close the file after the file is used up.

In [93]: with open('E:/Python Basics/test.txt','r') as fb:
    ...:     data =
In [95]: fb.closed
Out[95]: True


As mentioned above, writing a non string to a file is not allowed. Is there any way to save a dictionary or list of data? The pickle module can store and read this serialization:

In [96]: import pickle
In [97]: list1 = ['nai','tang','mao',1,2,3]

In [98]: pic_f = open('E:/Python Basics/list.pkl','wb')
In [99]: pickle.dump(list1,pic_f)
In [100]: pic_f.close()

The dump() method receives two parameters. The first is the content to be stored and the second is the stored file object. After the operation, you also need to close the file object with close(). After storage, you can use the load() method to load the content in the file.

In [102]: pic_f = open('E:/Python Basics/list.pkl','rb')
In [103]: list2 = pickle.load(pic_f)

In [104]: list2
Out[104]: ['nai', 'tang', 'mao', 1, 2, 3]
In [105]: pic_f.close()

When using pickle to store or read, you should pay attention to operating file objects in binary form, that is, 'wb' and 'rb'. Pickle is very suitable for storing data with complex data types and a large amount of data.

Keywords: Python

Added by rpupkin77 on Sun, 26 Dec 2021 10:52:39 +0200