Python3基礎之(十 五)讀寫檔案1
阿新 • • 發佈:2018-11-16
一、\n
換行命令
定義 text 為字串, 並檢視使用 \n 和不適用 \n 的區別:
>>> text='this is first line,this is second line,this is third line'
>>> print(text)
this is first line,this is second line,this is third line
>>> text='this is first line\n,this is second line\n,this is third line\n'
>> > print(text)
this is first line
,this is second line
,this is third line
# 輸入換行命令\n,要注意斜杆的方向。注意換行的格式和c++一樣
二、open 讀檔案方式
使用 open
能夠開啟一個檔案, open
的第一個引數為檔名和路徑 ‘my file.txt’,
第二個引數為將要以什麼方式開啟它, 比如 w
為可寫方式.
如果計算機沒有找到 ‘my file.txt’
這個檔案, w
方式能夠建立一個新的檔案, 並命名為 my file.txt
if __name__=='__main__' :
text='hello world'
# 用法: open('檔名','形式'), 其中形式有'w':write;'r':read.
my_file = open('my file.txt', 'w')
my_file.write(text) # 該語句會寫入先前定義好的 text
my_file.close() # 關閉檔案
三、\t tab 對齊
使用 \t 能夠達到 tab 對齊的效果:
if __name__=='__main__':
text='\thello world\n \thello \n \tworld\n'
my_file = open('my file.txt', 'w') # 用法: open('檔名','形式'), 其中形式有'w':write;'r':read.
my_file.write(text) # 該語句會寫入先前定義好的 text
my_file.close() # 關閉檔案
命令列中展示一下區別
有\t
>>> text='\thello world\n \thello \n \tworld\n'
>>> print(text)
hello world
hello
world
沒有\t
>>> text='hello world\nhello\nworld\n'
>>> print(text)
hello world
hello
world