python 文件 读取
时间: 2023-09-06 18:12:36 浏览: 52
Python文件读取有多种方式,常见的有以下几种方法:
1. 使用with open()语句直接打开并读取文件。这种方式可以逐行读取文件内容,并将每行作为一个字符串进行处理。例如:
with open('filepath', 'r') as f:
for line in f:
print(line)
[1]
2. 按行读取文件内容。这种方法可以逐行读取文件,并将每行内容作为一个字符串返回。例如:
f1 = open("C:/Users/Administrator/Desktop/qj_ly_product_list.txt", 'r', encoding='UTF-8')
for i in f1:
print(i, end='')
[2]
3. 读取整个文件并将内容存储在一个字符串变量中。这种方法适用于文件大小适中的情况,如果文件过大,可能会超出可用内存。例如:
file_object = open("test.py", 'r')
try:
all_the_text = file_object.read()
print(type(all_the_text))
print("all_the_text=", all_the_text)
finally:
file_object.close()
[3]
以上就是Python文件读取的几种常见方法。可以根据实际需求选择适合的方法进行文件读取操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Python 文件读取的4种方式](https://blog.csdn.net/Decennie/article/details/119223021)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [python读取文件方法详解](https://blog.csdn.net/qnlailai/article/details/108042154)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [python读取文件的几种方式](https://blog.csdn.net/qq_42759120/article/details/125283271)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]