Ⅰ Python讀取文件內容的方法有幾種
filename=open('i:\\install\\test.txt','r+')#讀取xx路徑xx文件;r+代表的是讀寫並存方式 print filename.read()#讀取所有的文件
Ⅱ 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'])
(2)python讀取hdf文件擴展閱讀:
python控制語句
1、if語句,當條件成立時運行語句塊。經常與else, elif(相當於else if) 配合使用。
2、for語句,遍歷列表、字元串、字典、集合等迭代器,依次處理迭代器中的每個元素。
3、while語句,當條件為真時,循環運行語句塊。
4、try語句,與except,finally配合使用處理在程序運行中出現的異常情況。
5、class語句,用於定義類型。
6、def語句,用於定義函數和類型的方法。
Ⅲ 大家好,我想用python代碼批量打開一個文件夾中的所有HDF文件,然後進行處理。
indir_lsta=r'E:/MODIS_LST/Aqua_2008/MS'
indir_lstt=r'E:/MODIS_LST/Terra_2008/MS'
把斜杠換一下
因為no such file就是找不到文件 ,改一下斜杠就可以了。我之前也遇到過這個問題。
如果還不行嗎,要麼就是文件位置或者格式出錯。
Ⅳ python中怎麼讀取文件內容
用open命令打開你要讀取的文件,返回一個文件對象
然後在這個對象上執行read,readlines,readline等命令讀取文件
或使用for循環自動按行讀取文件
Ⅳ python 讀取大文件數據怎麼快速讀取
python中讀取數據的時候有幾種方法,無非是read,readline,readlings和xreadlines幾種方法,在幾種方法中,read和xreadlines可以作為迭代器使用,從而在讀取大數據的時候比較有效果.
在測試中,先創建一個大文件,大概1GB左右,使用的程序如下:
[python] view plainprint?
import os.path
import time
while os.path.getsize('messages') <1000000000:
f = open('messages','a')
f.write('this is a file/n')
f.close()
print 'file create complted'
在這里使用循環判斷文件的大小,如果大小在1GB左右,那麼結束創建文件。--需要花費好幾分鍾的時間。
測試代碼如下:
[python] view plainprint?
#22s
start_time = time.time()
f = open('messages','r')
for i in f:
end_time = time.time()
print end_time - start_time
break
f.close()
#22s
start_time = time.time()
f = open('messages','r')
for i in f.xreadlines():
end_time = time.time()
print end_time - start_time
break
f.close()
start_time = time.time()
f = open('messages','r')
k= f.readlines()
f.close()
end_time = time.time()
print end_time - start_time
使用迭代器的時候,兩者的時間是差不多的,內存消耗也不是很多,使用的時間大概在22秒作用
在使用完全讀取文件的時候,使用的時間在40s,並且內存消耗相當嚴重,大概使用了1G的內存。。
其實,在使用跌倒器的時候,如果進行連續操作,進行print或者其他的操作,內存消耗還是不可避免的,但是內存在那個時候是可以釋放的,從而使用迭代器可以節省內存,主要是可以釋放。
而在使用直接讀取所有數據的時候,數據會保留在內存中,是無法釋放這個內存的,從而內存卡死也是有可能的。
在使用的時候,最好是直接使用for i in f的方式來使用,在讀取的時候,f本身就是一個迭代器,其實也就是f.read方法