Python基礎學習 五 讀寫檔案

2021-09-19 23:24:47 字數 2454 閱讀 7610

首先需要了解換行命令 : \n

text='this is my first test. this is the second line. this the third '

print(text) # 無換行命令

"""this is my first test. this is the second line. this the third

"""text='this is my first test.\nthis is the second line.\nthis the third line'

print(text) # 輸入換行命令\n,要注意斜桿的方向。注意換行的格式和c++一樣

"""this is my first test.

this is the second line.

this the third line

"""

使用open能夠開啟乙個檔案,open的第乙個引數為檔名和路徑 『my file.txt』, 第二個引數為將要以什麼方式開啟它, 比如w為可寫方式. 如果計算機沒有找到 『my file.txt』 這個檔案,w方式能夠建立乙個新的檔案, 並命名為my file.txt

my_file=open('my file.txt','w')   #用法: open('檔名','形式'), 其中形式有'w':write;'r':read.

my_file.write(text) #該語句會寫入先前定義好的 text

my_file.close() #關閉檔案

我們先儲存乙個已經有3行文字的 「my file.txt」 檔案, 檔案的內容如下:

this is my first test. 

this is the second line.

this the third

my_file.close()

""""

this is my first test.

this is the second line.

this the third line.

""""

#執行後再去開啟檔案,會發現會增加一行**中定義的字串

使用file.read()能夠讀取到文字的所有內容.

file= open('my file.txt','r') 

content=file.read()

print(content)

""""

this is my first test.

this is the second line.

this the third line.

""""

如果想在文字中一行行的讀取文字, 可以使用file.readline(),file.readline()讀取的內容和你使用的次數有關, 使用第二次的時候, 讀取到的是文字的第二行, 並可以以此類推:

file= open('my file.txt','r') 

content=file.readline() # 讀取第一行

print(content)

""""

this is my first test.

""""

second_read_time=file.readline() # 讀取第二行

print(second_read_time)

"""this is the second line.

"""

如果想要讀取所有行, 並可以使用像for一樣的迭代器迭代這些行結果, 我們可以使用file.readlines(), 將每一行的結果儲存在list中, 方便以後迭代.

file= open('my file.txt','r') 

content=file.readlines() # python_list 形式

print(content)

""""

""""

# 之後如果使用 for 來迭代輸出:

python基礎 檔案讀寫

1.讀寫方式 f open text r encoding utf 8 2.寫讀方式 f open text w encoding utf 8 3.追加方式 f open text a encoding utf 8 4.讀方式 f open text r encoding utf 8 5.寫方式 f...

python基礎 讀寫檔案

import os print os.getcwd import os os.chdir 你想要的路徑 import os os.makedirs 你想要的檔案目錄 import os print os.path.abspath demo import os print os.path.isabs ...

python檔案讀寫(基礎)

1.開啟檔案 讀寫檔案是常見的io操作,python內建了讀寫檔案的函式,方便了檔案的io操作。檔案讀寫之前需要開啟檔案,確定檔案的讀寫模式。open函式用來開啟檔案,語法如下 open name,mode,buffering open函式使用乙個檔名作為唯一的強制引數,然後返回乙個檔案物件。模式 ...