Python读写文件
File Handling的Python File Write 1
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
1.通過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()):
2.通過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'):
enumerate跳過某行
f_data = open(file_app, "r").read()
for i,line_app in enumerate(f_data.splitlines()):
if i == 0:
continue
打开文件的方式(a a+ r r+ w w+)
这里是引用
The argument mode points to a string beginning with one of the following
sequences (Additional characters may follow these sequences.):
r —— Open text file for reading. The stream is positioned at the
beginning of the file.
r+ —— Open for reading and writing. The stream is positioned at the
beginning of the file.
w —— Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
w+—— Open for reading and writing. The file is created if it does not
exist, otherwise it is truncated. The stream is positioned at
the beginning of the file.
a—— Open for writing. The file is created if it does not exist. The
stream is positioned at the end of the file. Subsequent writes
to the file will always end up at the then current end of file,
irrespective of any intervening fseek(3) or similar.
a+—— Open for reading and writing. The file is created if it does not
exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current
end of file, irrespective of any intervening fseek(3) or similar.
写入文件错误-OSError-Errno 22
OSError: [Errno 22] Invalid argument: 'D:\\codework\\python\\GlobalNet\x0cile\\hosts'
open(‘D:\codework\python\GlobalNet\file\hosts’, ‘w’, encoding=‘utf-8’)
更正,\轉義符號會\f轉義,從而造成錯誤解析
open(‘D:\codework\python\GlobalNet\file\hosts’, ‘w’, encoding=‘utf-8’)