Python 檔案讀寫基礎操作例項

2021-08-04 22:10:21 字數 1173 閱讀 2841

本文針對python入門者提供了乙個檔案讀寫的例項,並且對程式進行了詳細的分析,保證剛接觸到python的入門者能理解。

**如下:

"""

created on aug 3 2007

@author:suqi791776

"""def

main

(): infile = open("test1.txt","r") #test1 is a defined name; r

#represents the process mode of test1 is read;

outfile = open("test2.txt","w")# w represents the process mode

#of test2 is write;

countlines = countlens = 0

#define two varibles respectively

#represents the number of lines and char

for line in infile

countlines += 1

#the number of line adding

countlens += len(line) #the number of char adding

outfile.write(line) #copy test1 to test2 line by line

infile.close() #close the test1

outfile.close() #close the test2

main()

注意:

infile = open(「test1.txt」,」r」)

語句中,檔名test1要加檔案型別限制,如果僅僅是

infile = open(「test1」,」r」)

就會報錯:

filenotfounderror: [errno 2] no such file or directory: 『test1』

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函式使用乙個檔名作為唯一的強制引數,然後返回乙個檔案物件。模式 ...