Just finished the Qingming holiday, now the weekend is over, blink of an eye is Tuesday.

I wonder if you will feel the same way in the years to come:

More and more big guy around, the gap is getting bigger and bigger, I can’t stop;

Everyone is doing sideline business to make money, I also want to catch up;

During the holiday, my colleagues and roommates are learning courses, so I also need to register to improve myself.

I was afraid that if I didn’t work hard for a day, I would be far behind.

We are always unconsciously competing with others, competing with others in their world, making ourselves out of breath and living with great anxiety.

Files and Exceptions (1)

In this article you can learn:

  • Read and write text files
  • Processing data set
  • Process command line arguments
  • Throws and handles exceptions

Read and write text files

Examples of text files include not only files created using a simple text editor such as Windows Notepad, but also Python source code files and HTML files. In the course that follows, you will learn how to work with data in files. Document processing is a very useful skill in many disciplines because analyzing or processing large data sets is often stored in files.

Open the file

In order to access the file, you must first open it. When you open the file, you specify the name of the file, or you prefix the path to the file name if the file is stored in another folder. Note that when the file to be opened is in the same path as the code file, we only say to write the file name directly. Assuming that you now want to read data from a file named input.txt in the same folder as the program, you can use the following function to open the file:

infile = open('input.txt'.'r')
Copy the code

This statement can open files in read mode represented by the string argument “r” and returns a file object associated with the input.txt file. When a file is opened in read mode, the file must exist; otherwise, an exception will be raised.

The file object returned by the open call must be stored in a variable through which all processing of the file can be done.

To open a file in write mode, you supply the filename as the first argument to the open function and the string “w” as the second argument:

outfile = open('output.txt'.'w')
Copy the code

If the output file already exists, it is emptied before writing new data. If the file does not exist an empty file. After processing the file, be sure to use the close method to close the file.

infile.close()
outfile.close()
Copy the code

If your program opens the file in write mode and does not close it in time to exit, some of the output may not be written to the disk file.

Once the file is closed, it cannot be used again until it is reopened. Attempting to do so will result in an exception.

Read the file

To read a line of text from a file, call the readline method that returns the file object when the file is opened:

line = infile.readline()

When a file is opened, the input tag is positioned at the beginning of the file. The readline method reads the text from the current position until the end of the line is encountered, at which point the input marker is moved to the next line. The readline method returns the read text, including a newline character representing the end of the line.

Suppose the input.txt file contains the following lines:

flying 
circus
Copy the code

The first time you call the readline method, you get the string ‘flying\n’, where \n represents the newline character at the end of a line. If you call the readline method again, the string ‘circus/n’ is returned. Calling the readline method again returns an empty string.

To read multiple lines of text from a file, we just need to read one line repeatedly and process it, because we have reached the end of the file. If the file contains an empty line, the readline method returns a string containing only the newline character ‘\n’.

infile = open('input.txt'.'r')
line = infile.readline()
whileline! =' ':
	print(line)
	line = infile.readline()
Copy the code

The warning value is an empty string, which is what the readline method returns after the end of the file is reached.

Like the input method, the readline method can only return strings. If the file contains numeric data, use int or float functions to convert the string to a numeric value.

Such as:

value = int(line)
Copy the code

Note: When converting a string to a value, the trailing newline character is ignored.

Written to the file

You can write text to a file that opens in write mode. This is done through the write method of the file object. For example, we could write the string ‘Hello World’ to the output file using the following statement;

outfile = open('outfile.txt'.'w')
outfile.write('Hello World\n')
Copy the code

The write method of the file object takes a single string as an argument and writes the string immediately. The string is appended to the end of the file, and you must explicitly write a newline character to start another line.

count = 10
totle = 8.252
outfile = open('outfile.txt'.'a')
outfile.write('Number of entries: %d\nTotal: %8.2f\n' % (count, totle))
Copy the code

Note: You need to open the file in append mode, as indicated by passing the string argument ‘a’.

Instead, you can use the print function to write text to the file. You need to supply the file object as the value of the parameter file.

outfile = open('outfile.txt'.'a')
print('Hello World', file=outfile)
Copy the code

Document processing practice

Suppose you have a text file that contains a series of floating-point numbers, one float per line. You need to read these values and write them to a new output file, align them by column, and then write their sum and square values.

The document reads as follows:

32.0
45.0
50.0
60.2
78.3
Copy the code
# #
# This program is used to read a file containing a number and then write to another file
Align by column, and finally write their sum and average
Prompt the user for input and output file names

inputFileName = input('Input file name: ')
outputFileName = input('Output file name: ')


Open input files and output files
infile = open(inputFileName, 'r')
outfile = open(outputFileName, 'w')

Read the input file and write out the output file
total = 0.0
count = 0

line = infile.readline()
whileline ! =' ':
	value = float(line)
	outfile.write('% 15.2 f \ n' % value)
	total = total + value
	count = count + 1
	line = infile.readline()


outfile.write('%15s\n' % '-- -- -- -- -- -- -- -- -- -- -- -- --')
outfile.write('Total: % 6.2 f \ n' % total)
print(count)
avg = total / count
outfile.write('business: % 6.2 f \ n' % avg)
infile.close()
outfile.close()
Copy the code

Easy wrong prompt

1. Backslashes in files

When you specify a filename using a string constant and the filename contains backslash characters, you must write each backslash twice:

infile = open('D:\ github\\Python_base\\ Chapter 7 files and exceptions \\ code demo\ input.txt')
Copy the code

Backslashes inside a string are escaped characters that form a special meaning with the next character. For example, \n represents a newline, and the combination of \\ represents a single backslash

However, when a user provides a file name for a program, the user should not type a backslash twice.

2. Open the file

When a file is opened in read mode, the file must exist otherwise an exception will occur. The file object must call the close method to close the file, whether it is opened read or written.

Self test

Infile = open(‘ ‘, ‘r’

Infile = open(‘input.txt’, ‘r’)

3. What is wrong with the following code?

infile = open('input.txt'.'r')
infile.close()
line = infile.readline()
whileline ! =' ':
   print(line)
   line = infile.readline()
Copy the code

4. How do we put ‘Hello World! ‘Write to output file?

Hello,
World!
Copy the code

The last

Confusion not only blocks the way ahead, but also makes us unable to see the direction of the future, making us more anxious and life more depressed……

In the face of every failure, we must believe:

This is not the end, not even the beginning of the end, but the end of the beginning.

After reading feel there is a harvest, you can point to the book [in watching], I hope we can go forward, find their own way.

I am a person who concentrates on learning. The more you know, the more you don’t know, the more wonderful content. See you next time!