python 檔案操作 深度學習

2022-05-17 02:43:26 字數 2397 閱讀 5111

obj = open('路徑',mode='模式',encoding='編碼')

obj.write()

obj.read()

obj.close()

基本模式

#開啟檔案

f=open('要開啟檔案路徑',mode='r/w/a/',encoding='檔案原來編碼') #f為接收變數

#操作檔案

data = f.()  # 讀取檔案內部全部內容,data為接收內容

f.write('要寫內容')

#關閉檔案

f.close()

#檔案開啟新操作,自動關閉

with open('text.txt',mode= 'a',encoding='utf-8') as v:

data = a.read()

# 縮排中的**執行完畢之後自動關閉

wd 模式傳入的是二進位制檔案,想寫入字串需要進行轉換操作

要把寫入內容先轉化為二進位制語言(encode)

wd再將二進位制檔案寫入檔案

r/rb

a/ab

write(字串)

obj = open('a.txt',mode='w',encoding='utf-8')

obj.write('中午你')

obj.close()

write(二進位制)

obj = open('a.txt',mode='wb')

​# obj.write('中午你'.encode('utf-8'))

v = '中午你'.encode('utf-8')

obj.write(v)

obj.close()

seek(游標位元組位置),無論模式是否帶b,都是按照位元組進行處理。

obj = open('a.txt',mode='r',encoding='utf-8')

obj.seek(3) # 跳轉到指定位元組位置

data = obj.read()

obj.close()

​print(data)

​obj = open('a.txt',mode='rb')

obj.seek(3) # 跳轉到指定位元組位置

data = obj.read()

obj.close()

​print(data)

tell(), 獲取游標當前所在的位元組位置

obj = open('a.txt',mode='rb')

# obj.seek(3) # 跳轉到指定位元組位置

obj.read()

data = obj.tell()

print(data)

obj.close()

flush,強制將記憶體中的資料寫入到硬碟

v = open('a.txt',mode='a',encoding='utf-8')

while true:

val = input('請輸入:')

v.write(val)

v.flush()

​v.close()

文藝

v = open('a.txt',mode='a',encoding='utf-8')

​v.close()

二逼

with open('a.txt',mode='a',encoding='utf-8') as v:

data = v.read()

# 縮排中的**執行完畢後,自動關閉檔案

with open('a.txt',mode='r',encoding='utf-8') as f1:

data = f1.read()

new_data = data.replace('飛灑','666')

​with open('a.txt',mode='w',encoding='utf-8') as f1:

data = f1.write(new_data)

大檔案修改

with open('a.txt',mode='r',encoding='utf-8') as f1,open('b.txt',mode='w',encoding='utf-8') as f2:#開啟檔案a,b

for line in f1:#按行取a的內容

new_line = line.replace('666','999')#修改內容

f2.write(new_line)#修改後的寫入b,完成修改

深度學習python

squeeze 降維 維度為1的降掉 tf.squeeze arr,降維,將維度為1 的降掉 arr tf.variable tf.truncated normal 3,4,1,6,1 stddev 0.1 arr2 tf.squeeze arr,2,4 arr3 tf.squeeze arr 降掉...

Python學習 檔案操作

python使用open來開啟資料流 data open data.txt 下面是乙個讀取乙個檔案,然後逐行輸出的 try data open data.txt for each line in data try role,line spoken each line.split 1 print ro...

Python學習筆記《檔案操作》

python的檔案操作容易上手,我選取了一些比較常用的。keep 開啟檔案 和c有點相像 f open friend.cpp 會讀取出來整個檔案的內容 小心記憶體不夠 f.read f.close with open friend.cpp as f f.read 逐行讀取 readlines 可以返...