name = 'sweet1'
file1 = open('%s.v' % name, 'w') # 不指定路徑則在絕對路徑生成,另外生成的檔名可以使用%替換
file2 = open('sweet2.v', 'r') # file1中的'w'代表可對該檔案進行寫入操作,而'r'代表唯讀
file1.close() # 關閉檔案
file2.close()
# 還可使用下面的方式開啟檔案
with open('sweet2.v', 'w') as file2: # 這樣不需要呼叫.close()來關閉檔案,語句執行完後自動關閉
# 在這裡執行對檔案file2的操作
import os
oldname = 'old.dat'
# 指定路徑:'d:\old.dat'
newname = 'new.data'
os.rename(oldname, newname)
os.rename(oldname, '%s' % newname) # 同樣可以替換
import re
file1.write() # 寫入
x = file2.read() # 讀取,該方式會將file檔案中所有的字元讀給變數x
# 可用splitlines將其按行分成字串列表,通過下標訪問每一行
y = file2.read().splitlines()
file2.truncate() # 清空
2 Python 檔案基本操作
file1.write 張飛 file1.close file3 open name.txt a file3.write n諸葛亮 file3.close file2 open name.txt print file2.read file2.close 輸出 張飛 諸葛亮 列印檔案指標的位置 fil...
python入門2 Python入門2
1列表和元組 列表 當索引超出了範圍時,python會報乙個indexerror錯誤 usr bin env python3 coding utf 8 列印s的1,v,9.注意 索引計數從 0 開始 s 1,2,3 a v b 7,8,9 列印1 print s 0 0 列印v print s 1 ...
2 Python內建函式
位元組陣列和位元組,3個引數 source,encoding,errors 當source引數為字串時,encoding引數也必須提供,函式將字串使用str.encode方法轉換成位元組陣列 當3個引數都不傳的時候,返回長度為0的位元組陣列 當source引數為整數時,返回這個整數所指定長度的空位元...