有個地方需要注意,我路徑中有 \t 在python中會被定義為轉義字元,在路經前加上r就會避免這種情況。
rstrip避免多出現空行
優化了一下
test_path = r'f:\python\test.txt'
with
open
(test_path)
as test1:
lines = test1.readlines(
)pi_string =
''for line in lines:
pi_string += line.strip(
)print
(pi_string[:15
]+'...'
)#只列印前十五位
print
(len
(pi_string)
)#統計一下他原來有多少位
寫入檔案
filename =
'text2.txt'
with
open
(filename,
'w')
as file_object:
file_object.write(
'i love you.'
)
讀取模式』r』寫入模式』w』附加模式』a』
如果寫入的檔案不存在,就會自動建立。
如果寫入多行,要用換行符
如果你不希望刪掉檔案原來的內容,就用附加模式進行寫入
python中檔案的相關操作和函式
fp open 檔名 mode 模式 encoding utf 8 fp 檔案的io物件 檔案控制代碼 i input 輸入 o output 輸出 一.檔案的寫入 1.開啟檔案 fp open ceshi1.txt mode w encoding utf 8 2.寫入內容 fp.write 把內容...
python中檔案操作
在python,使用open函式,可以開啟乙個已經存在的檔案,或者建立乙個新檔案 open 檔名,訪問模式 關閉檔案 若沒有test.py,新建乙個檔案 f open test.py w 關閉檔案 f.close 複製檔案流程 分析 1.獲取使用者要複製的檔名 2.開啟這個檔案 3.新建乙個檔案 4...
python中檔案操作
一 檔案的基本作用 1 檔案操作步驟 1 開啟 語法 open name,mode,encoding 編碼格式 name 是要開啟的目標檔名的字串 可以包含檔案所在的具體路徑 mode 設定開啟檔案的模式 訪問模式 唯讀 寫入 追加 encoding 檔案裡內容的編碼格式 2 讀寫 寫入 檔案物件....