Home>Article>Backend Development> How to read txt file in python
How to read txt files in python?
First, create a txt document on the desktop and enter the following content:
你好。 Hello. abcdefg 啊不错的风格
View the properties of the file and obtain the absolute value of the file Path:
D:\HintSoft\Hint-W7\Desktop
The file name is——New text document.txt,
Then, the absolute path plus the file name is the absolute file name:
D:\HintSoft\Hint-W7\Desktop\新建文本文档.txt
Open this file with python and name it f.
f = open(r"D:\HintSoft\Hint-W7\Desktop\新建文本文档.txt",'r')
There is no output above, because after opening the file, the content has not been read:
f = open(r"D:\HintSoft\Hint-W7\Desktop\新建文本文档.txt",'r') s=f.read() print(s)
In this way, python returns all the information in the file .
What if we only want to read the first 6 characters?
f = open(r"D:\HintSoft\Hint-W7\Desktop\新建文本文档.txt",'r') s=f.read(6) print(s)
In this way, only the first 6 characters will be returned.
Related recommendations: "Python Tutorial"
The above is the detailed content of How to read txt file in python. For more information, please follow other related articles on the PHP Chinese website!