Starfruit Python Advanced Lecture 6-Export and Write Files

My CSDN blog column: https://blog.csdn.net/yty_7

Github address: https://github.com/yot777/

 

6.1 Python output

Like most languages, Python also uses the print () function to output. For example, we are already familiar with the output line Hello World

#Python的print函数举例1
>>> print("Hello World")
Hello World

Simply put the string to be output into the print () function. There are several methods of use in specific use:

1. The print () function can be used to output the value of a variable. The usage is to add a (comma) variable name after the string prompt . as follows:

#Python的print函数举例2
>>> a=5
>>> print("a=",a)
a= 5
>>> k = [1,2,3,4,5]
>>> print("k=",k)
k= [1, 2, 3, 4, 5]
#同时输出两个变量的值
>>> a=5
>>> b=6
>>> print("a=",a,"b=",b)
a= 5 b= 6

Careful students will find that there is an extra space between a = and 5, and an extra space between b = and 6, which sometimes cannot meet our output format requirements.

2. C language can use the legacy % as a keyword written, the format of the output is set as follows:

#Python的print函数举例3
>>> today='Sunday'
>>> wendu=15.1
>>> shidu=53
>>> days=10
>>> print("今天是%s,温度是%.3f度,湿度是%f%%,是我学习Python的第%d天" %(today, wendu, shidu, days))
今天是Sunday,温度是15.100度,湿度是53.000000%,是我学习Python的第10天

In this example, today, wendu, shidu, and days are strings, floating-point numbers, floating-point numbers, and integers, respectively. Python uses the % keyword of the C language , as described below:

(1) % s means output string, % f means output floating point, % d means output integer, if you want to output a real percent sign, you need to write two percent signs.

(2) % f can limit the number of decimal places output, % .1f (percent sign 1f) means output 1 decimal place, and % .2f (percent sign point 2f) means output 2 decimal places. If % f has no decimal places, 6 decimal places will be output.

(3) The variables represented by the% keyword, after outputting the prompt, use the % variable name (if there are multiple variables, you need to add parentheses) to list them one by one, the variable order must be the same as the% keyword . In this example:% s corresponds to today,% .3f corresponds to wendu,% f corresponds to shidu,% d corresponds to days

(4) There is no comma between the output prompt and the % variable name ! This beginner is easy to confuse with the first method, for example:

#Python的print函数举例4
>>> k=0.0
>>> print("k=",k)      #变量k和输出提示符之间是逗号
k= 0.0                 #输出结果和k=之间有个空格
>>> print("k=%f" %k)   #变量%k和输出提示字符之间是空格
k=0.000000             #输出结果和k=之间没有空格
>>> print("k=%d" %k)
k=0                    #本来变量k是浮点数,现在按照整数输出

(5)% f can also limit the number of integers before the decimal point of the output.% D and% s can also control the output format. For details, please refer to the relevant manual.

3. You can use the Java-like + connector to connect the output prompt and variables. We rewrite Example 3 as follows:

#Python的print函数举例4
>>> today='Sunday'
>>> wendu=15.1
>>> shidu=53
>>> days=10
>>> print("今天是"+str(today)+",温度是"+str(wendu)+"度,湿度是"+str(shidu)+"%,是我学习Python的第"+str(days)+"天")
今天是Sunday,温度是15.1度,湿度是53%,是我学习Python的第10天

described as follows:

(1) When using the + connector, each variable must be converted to a string type, so there are str (today), str (wendu) ... If you do n’t use this, you will get an error:

>>> print("今天是"+str(today)+",温度是"+str(wendu)+"度,湿度是"+str(shidu)+"%,是我学习Python的第"+days+"天")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int     #days没有转换为字符串类型,报错

(2) Pay attention to the relationship between quotation marks and variables. The quotation marks surround the output prompt, and the variables do not need to be enclosed in quotation marks

(3) Use the + connector to connect the output prompt and the variable. Pay attention to the output format and the number of variables. The quotation marks appear in pairs, and the + connector also appears in pairs.

 

After the print () function is output, it will wrap by default. You can add end = "" in the parameter to change the output multiple lines into one line, or add your favorite separator, for example as follows:

#Python的print函数举例5
print("今天天气真好啊")           #没有end参数默认表示print()函数输出之后换下一行
print("我想出去玩")
print("有人一起吗")
运行结果:
今天天气真好啊
我想出去玩
有人一起吗

print("今天天气真好啊",end="")      #end=""表示print()函数输出之后不换行
print("我想出去玩",end="")
print("有人一起吗")
运行结果:
今天天气真好啊我想出去玩有人一起吗

print("今天天气真好啊",end=",")    #end=","表示print()函数输出之后以逗号分隔下一个输出
print("我想出去玩",end=",")
print("有人一起吗")
运行结果:
今天天气真好啊,我想出去玩,有人一起吗

In addition to output, the print () function is more important for use as a debugger. When writing complex judgments and looping conditions, we often cannot directly think of the results of the execution. We need to use the print () function to display the running status of the program in real time to help us judge whether there is a problem with the logic of the program.

When the Python file was read in the previous section, we used the print () function to debug the program:

#定义一个空列表lineArr 
lineArr = []
#打开源文件test.txt
f = open('test.txt')
#readlines() 读取整个文件,自动将文件内容分析成一个包含所有行的列表lines
lines = f.readlines()
#遍历lines的每一行line
for line in lines:
    #将每一行先去掉回车,再以Tab符作为元素之间的分隔符号
    linenew = line.strip().split('\t')
    #len(linenew)是linenew列表长度,也就是linenew列表的元素个数
    #for in in range(m)表示i从0增加到m-1
    for i in range(len(linenew)):
    	#从linenew[0]到linenew[m-1]的每个元素都转为整型数字
    	linenew[i] = int(linenew[i])
    #将当前行的内容添加到列表lineArr 
    lineArr.append(linenew)
    #打印出当前的lineArr列表
    print("lineArr:", lineArr)
#打印出最终的lineArr列表
print("最终的lineArr:",lineArr)
#关闭文件
f.close()
 
运行结果:
lineArr: [[1, 2, 3, 4, 5]]
lineArr: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
lineArr: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
lineArr: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
最终的lineArr: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]

The above code only needs to print out the final lineArr list and output it, but we printed the content of each line and added it to the list lineArr, so that it is very clear to see that this program does realize reading source files by line .TXT

The print () function will appear repeatedly as a function of the debugger in the future. As an important means for us to understand the logic of complex programs, everyone must be familiar with it.

 

6.2 Python write file

Writing a file is similar to reading a file, and is divided into the following steps:

1. Open the file and use the open () function to generate a file object f. Note that the parameters of the open () function are different from when they are read, as follows:

f = open('test.txt', 'r')  #读取test.txt文件的内容
f = open('test.txt', 'w')  #向test.txt文件写入内容
f = open('test.txt', 'r+')  #既可以读取test.txt文件,也可以写入test.txt文件

2. To write to a file, use the write () method of the file object file

3. To close the file, use the close () method of the file object file

Similarly, you can use the with statement to automatically call the close () method for us:

with open(filename, 'w') as f:
    f.write("Add a word")

Examples of file writing are as follows:

(1) Write an empty file (overwrite)

#写入空文件(覆盖)
filename = 'test.txt'
with open(filename, 'w') as file_object:
    file_object.write("Add a word")

After running this code, if the write file does not exist, the open () function will automatically create a test.txt file in the current directory of the py file, and then write Add a word

If the test.txt file already exists, the existing content will be emptied before writing to Add a word

You can write multiple lines, but if you don't add a line break, it will actually write to the same line in the file:

filename = 'test.txt'
with open(filename, 'w') as file_object:
    file_object.write("Add a word")
    file_object.write("Add two words")

operation result:

Write after adding a newline

filename = 'test.txt'
with open(filename, 'w') as file_object:
    file_object.write("Add a word\n")
    file_object.write("Add two words\n")

operation result:

(2) Add content to the original file

Change the parameter of open () function from w to a

filename = 'test.txt'
with open(filename, 'a') as file_object:
    file_object.write("abcdefj\n")
    file_object.write("hijklmn\n")
    file_object.write("opq\t")   #\t也可以作为分隔符,表示一个Tab键
    file_object.write("rst\n")
    file_object.write("uvw\t")
    file_object.write("xyz\n")

operation result:

 

to sum up:

The output of Python uses the print () function. You can use commas to output variable values, use the % keyword to output typed variable values, and use the + connector to connect the output prompt and variables.

The print () function defaults to a newline. You can add end = "" to the parameter to change the output multiple lines into one line.

In addition to output, the print () function is more important for use as a debugger.

Writing files in Python is similar to reading files. They are open, write, and close in three steps, but note that the parameters of the open () function are different from when they are read:

r is reading w is writing r + is both reading and writing a is additional writing based on the original file

 

My CSDN blog column: https://blog.csdn.net/yty_7

Github address: https://github.com/yot777/

If you think this chapter is helpful to you, welcome to follow, comment and like! Github welcomes your Follow and Star!

Published 55 original articles · won praise 16 · views 6111

Guess you like

Origin blog.csdn.net/yty_7/article/details/104338218