How can we extract content from a txt file using Python?
To access specific content within a txt file, you can utilize Python’s file handling capabilities. One common method is as follows:
- Open the txt file.
- Fetch the lines of the file.
- You can access specific rows in a list by using their indexes as needed.
- Close the file.
Here is an example code:
# 打开文件
with open('example.txt', 'r') as file:
# 读取所有行
lines = file.readlines()
# 获取部分内容
start_line = 2
end_line = 5
content = lines[start_line:end_line]
# 打印内容
for line in content:
print(line.strip())
# 关闭文件
file.close()
In the code above, we opened a file named example.txt, read all its lines using the readlines() function, and stored them in a list called lines. Then, we specified the starting and ending lines of the content we want to retrieve, extracted the corresponding lines from the lines list. Finally, we used a loop to iterate over and print the selected content.
Please note that the above example assumes the txt file already exists in the current working directory. If the file is located in a different directory, you will need to provide the full file path.