1. 程式人生 > >python初學筆記(2)

python初學筆記(2)

檔案處理:

讀檔案:

f1 = file("D:\\document_classification\\sports_urlFilePair.txt",'r')

while True:
    line = f1.readline()
    if(line == "\n" or line == ""):
        break
    tmp = line.split("\t")

寫檔案:

f2 = file("D:\\document_classification\\sports.txt","w")

f2.write()

目錄處理:

讀取目錄下的檔名稱及路徑:

for i in os.listdir(directory):
    string = directory+"\\"+i

新建目錄:

if(not os.path.exists(infoPageDirectory+ngram)):
        os.mkdir(infoPageDirectory+ngram)

判斷檔案/目錄是否存在:

import os
os.path.isfile('test.txt') #如果不存在就返回False
os.path.exists(directory) #如果目錄不存在就返回False

中文編碼:

import sys
reload(sys)
sys.setdefaultencoding('utf8')

line = line.decode("UTF-8")

len(line)

以引數輸入輸出:
import sys
reload(sys)

args = sys.argv
#input file
source = file(args[1],"r")
#output file
output = file(args[2],"w")