File Handling的Python File Write1
Write to an Existing File To write to an existing file, you must add a parameter to the open() function:
“a” - Append - will append to the end of the file “w” - Write - will
overwrite any existing content
Create a New File To create a new file in Python, use the open()
method, with one of the following parameters:“x” - Create - will create a file, returns an error if the file exist
“a” - Append - will create a file if the specified file does not exist
“w” - Write - will create a file if the specified file does not exist
通過Open讀寫(最簡單的讀寫方式)
f= open("file/bigData.csv","r")
f_reader = csv.reader(f)
for item in f_reader :
if f_reader.line_num == 1:
big_file_open.close()
#a+,打開文件並添加數據,如果文件不存在,則創建
f = open("file/bigData.csv", "a+")
#指定編碼格式
f = open(sql_template_file,"r",encoding='utf-8')
#通過enumerate讀取文件,可以記錄行號i
for i,line in enumerate(f.splitlines()):
通過With open讀寫
with open("file/bigData.csv") as f:
#line 讀取指定行
item1 = f.readlines()[line].split(",")[0]
#讀取 10 到 100 行區間數據
data = f.readlines()[10:100]
f.close()
返回文件頭,繼續讀取
#while循环结束后,指针到文件末尾
inputFile.seek(0) #返回文件头
line=inputFile.readline() #再次初始化,指向文件头
循環緩存數據
f_mt = open(file_mt, "r")
f_mt_data = f_mt.read()
for line_mt in f_mt_data.splitlines():
start_time_mt = line_mt.split(",")[0]
或者
for line in f_mt_data.split('\n'):
w3schools.com ↩︎