python讀取本地文件
❶ python怎麼讀取文件名的內容
python讀取文件內容的方法:
一.最方便的方法是一次性讀取文件中的所有內容並放置到一個大字元串中:
all_the_text = open('thefile.txt').read( )
# 文本文件中的所有文本
all_the_data = open('abinfile','rb').read( )
# 二進制文件中的所有數據
為了安全起見,最好還是給打開的文件對象指定一個名字,這樣在完成操作之後可以迅速關閉文件,防止一些無用的文件對象佔用內存。舉個例子,對文本文件讀取:
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
不一定要在這里用Try/finally語句,但是用了效果更好,因為它可以保證文件對象被關閉,即使在讀取中發生了嚴重錯誤。
二.最簡單、最快,也最具Python風格的方法是逐行讀取文本文件內容,並將讀取的數據放置到一個字元串列表中:
list_of_all_the_lines = file_object.readlines( )
這樣讀出的每行文本末尾都帶有"\n"符號;如果你不想這樣,還有另一個替代的辦法,比如:
list_of_all_the_lines = file_object.read( ).splitlines( )
list_of_all_the_lines = file_object.read( ).split('\n')
list_of_all_the_lines = [L.rstrip('\n') for L in file_object]
最簡單最快的逐行處理文本文件的方法是,用一個簡單的for循環語句:
for line in file_object:
process line
這種方法同樣會在每行末尾留下"\n"符號;可以在for循環的主體部分加一句:
lineline = line.rstrip('\n')
或者,你想去除每行的末尾的空白符(不只是'\n'\),常見的辦法是:
lineline = line.rstrip( )
❷ python怎麼將本地一個文件夾的所有文本讀進內存中
列出文件,把各個文件打開讀到bytes位元組串裡面.
比如
f=open("a.txt","rb")
a={}
a["a.txt"]=f.read()
f=open("b.txt","rb") #寫成對列版表的循環權
a["b.txt"]=f.read()
f=open("c.txt","rb") #寫成對列表的循環
a["c.txt"]=f.read()
❸ 使用python如何讀取本地json文件
具體情況具體分析,要看你的文件是什麼編碼,用的python哪個版本
❹ Python如何讀寫文本文件
1.open使用open打開文件後一定要記得調用文件對象的close()方法。比如可以用try/finally語句來確保最後能關閉文件。
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
註:不能把open語句放在try塊里,因為當打開文件出現異常時,文件對象file_object無法執行close()方法。
2.讀文件讀文本文件input = open('data', 'r')
#第二個參數默認為r
input = open('data')
讀二進制文件input = open('data', 'rb')
讀取所有內容file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
讀固定位元組file_object = open('abinfile', 'rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close( )
讀每行list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,還可以直接遍歷文件對象獲取每行:
for line in file_object:
process line
3.寫文件寫文本文件output = open('data.txt', 'w')
寫二進制文件output = open('data.txt', 'wb')
追加寫文件output = open('data.txt', 'a')
output .write("\n都有是好人")
output .close( )
寫數據file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
❺ Python 讀取文本文件,怎麼才能讀取一段內容
python讀取段落需要自定義函數:
from _ _future_ _ import generators
def paragraphs(fileobj, separator='\n'):
if separator[-1:] != '\n': separator += '\n' paragraph = []
for line in fileobj:
if line == separator:
if paragraph: yield ''.join(paragraph)
paragraph = []
else: paragraph.append(line)
if paragraph: yield ''.join(paragraph)
❻ python如何讀取文件的內容
# _*_ coding: utf-8 _*_
import pandas as pd
# 獲取文件的內容
def get_contends(path):
with open(path) as file_object:
contends = file_object.read()
return contends
# 將一行內容變成數組
def get_contends_arr(contends):
contends_arr_new = []
contends_arr = str(contends).split(']')
for i in range(len(contends_arr)):
if (contends_arr[i].__contains__('[')):
index = contends_arr[i].rfind('[')
temp_str = contends_arr[i][index + 1:]
if temp_str.__contains__('"'):
contends_arr_new.append(temp_str.replace('"', ''))
# print(index)
# print(contends_arr[i])
return contends_arr_new
if __name__ == '__main__':
path = 'event.txt'
contends = get_contends(path)
contends_arr = get_contends_arr(contends)
contents = []
for content in contends_arr:
contents.append(content.split(','))
df = pd.DataFrame(contents, columns=['shelf_code', 'robotid', 'event', 'time'])
(6)python讀取本地文件擴展閱讀:
python控制語句
1、if語句,當條件成立時運行語句塊。經常與else, elif(相當於else if) 配合使用。
2、for語句,遍歷列表、字元串、字典、集合等迭代器,依次處理迭代器中的每個元素。
3、while語句,當條件為真時,循環運行語句塊。
4、try語句,與except,finally配合使用處理在程序運行中出現的異常情況。
5、class語句,用於定義類型。
6、def語句,用於定義函數和類型的方法。
❼ python如何打開本地文件我哪裡有問題,剛學編程的。大家幫忙看看了,多謝!
A=open(r'xxxxxx','r')
fortxtinA.readlines():
print(txt)
A.close()
❽ python怎麼讀取TXT
Python的文本處理是經常碰到的一個問題,Python的文本文件的內容讀取中,有三類方法:read()、readline()、readlines(),這三種方法各有利弊,下面逐一介紹其使用方法和利弊。
read():
read()是最簡單的一種方法,一次性讀取文件的所有內容放在一個大字元串中,即存在內存中
file_object = open('test.txt') //不要把open放在try中,以防止打開失敗,那麼就不用關閉了try:
file_context = file_object.read() //file_context是一個string,讀取完後,就失去了對test.txt的文件引用
# file_context = open(file).read().splitlines()
// file_context是一個list,每行文本內容是list中的一個元素finally:
file_object.close()//除了以上方法,也可用with、contextlib都可以打開文件,且自動關閉文件,//以防止打開的文件對象未關閉而佔用內存read()的利端:
方便、簡單
一次性獨讀出文件放在一個大字元串中,速度最快
read()的弊端:
文件過大的時候,佔用內存會過大
readline()逐行讀取文本,結果是一個list
with open(file) as f: line = f.readline() while line:
print line
line = f.readline()readline()的利端:
佔用內存小,逐行讀取
readline()的弊端:
由於是逐行讀取,速度比較慢
**readlines()一次性讀取文本的所有內容,結果是一個list
with open(file) as f: for line in f.readlines():
print line這種方法讀取的文本內容,每行文本末尾都會帶一個' '換行符 (可以使用L.rstrip(' ')去掉換行符)
readlines()的利端:
一次性讀取文本內容,速度比較快
readlines()的弊端:
隨著文本的增大,佔用內存會越來越多
- file_object = open('test.txt','rU')try:
- for line in file_object:
- do_somthing_with(line)//line帶" "finally:
- file_object.close()
readline():
readlines():
最簡單、最快速的逐行處理文本的方法:直接for循環文件對象
❾ python怎麼讀取txt文件全部數據
Python 讀寫文本文件
首先需要注意的是,txt文件是具有字元編碼的,不同的txt字元編碼可能不同。具體是什麼編碼,可以用 notepad++ 等文本編輯器查看。
讀取文件建議使用 with...as... 結構,可以自動關閉文件。
withopen("text.txt","r")asf:
text=f.read()
print(text)
如果不用 with...as... 則必須手動關閉文件:
f=open("text.txt","r")
text=f.read()
f.close()
print(text)
如果讀取的文件含有中文,使用內置的open可能會報錯,這個時候要用到codecs模塊:
importcodecs
withcodecs.open("text.txt","r",encoding="utf-8")asf:
text=f.read()
print(text)
(假設 text.txt 是 utf-8 編碼)