Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Why does python open () automatically delete spaces after lines?
Why does python open () automatically delete spaces after lines?
When using the open () function to open a file in Python, if the file opening mode is not specified, it defaults to text mode. In this mode, blank characters (such as spaces and tabs) at the end of a text file line will be automatically deleted. This behavior is determined by the implementation of the Python interpreter, not by the operating system or file system.

If you want to keep the spaces after each line in the file, you can open the file in binary mode, so that the space characters at the end of the line will not be automatically deleted when reading the file. For example, when you open a file, specify the mode as "rb", that is, you can read the file in binary mode:

Use open('test.txt',' rb') as f:

contents = f.read()

Note that when you open a file in binary mode, what you read will be regarded as a byte string instead of a string, and you need to convert it accordingly. If you want to write a file in text mode, you need to explicitly add blank characters at the end of the line when writing.

If it helps you, please accept it. Thank you~