Total Pageviews

2016/03/09

[Python] File I/O example

Example 1: Read file and print its content

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import os

""" 列印檔案內容 (print file content) """
def printFileContent(file):
    try:
        if(isFileExists("D:\\python\\txt\\" + file)==True):
            """ r stands for read """
            data = open("D:\\python\\txt\\" + file, "r", encoding="utf-8")
            for each_line in data:
                print(each_line)
        
        else:
            print("查無檔案 : "+file)
    except IOError as err:
        print('IOError! ' + err.args[0])
    finally:
       data.close()

"""" 檢查檔案是否存在 """
def isFileExists(file):
 if os.path.exists(file):
  return True
 else:
  return False

Execution result:
1
2
3
4
5
6
7
>>> import myUtil
>>> myUtil.printFileContent("AJokeADay.txt")
A rancher asked his veterinarian for some free advice. 

I have a horse that walks normally sometimes, and sometimes he limps. What shall I do?

The Vet replied, The next time he walks normally, sell him.


Example 2: append some words at the end of file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import os

""" 在檔案內容末端增加文字 (add words at the end of file content) """
def appendString(file, content):
    try:
        if(isFileExists("D:\\python\\txt\\" + file) == True):
            """ a stands for append """
            data = open("D:\\python\\txt\\" + file, "a", encoding="utf-8")
            data.write("\n" + content)
        else:
            print("查無檔案:"+file)
    except IOError as err:
        print('IOError! ' + err.args[0])
    finally:
       data.close()  


""" 列印檔案內容 (print file content) """
def printFileContent(file):
    try:
        if(isFileExists("D:\\python\\txt\\" + file)==True):
            """ r stands for read """
            data = open("D:\\python\\txt\\" + file, "r", encoding="utf-8")
            for each_line in data:
                print(each_line)
        
        else:
            print("查無檔案 : "+file)
    except IOError as err:
        print('IOError! ' + err.args[0])
    finally:
       data.close()


"""" 檢查檔案是否存在 """
def isFileExists(file):
 if os.path.exists(file):
  return True
 else:
  return False

Execution result:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> import time
>>> addedContent = time.strftime("%Y/%m/%d")+" edited"
>>> myUtil.appendString("AJokeADay.txt", addedContent)
>>> 
>>> myUtil.printFileContent("AJokeADay.txt")
A rancher asked his veterinarian for some free advice. 

I have a horse that walks normally sometimes, and sometimes he limps. What shall I do?

The Vet replied, The next time he walks normally, sell him.

2015/12/23 edited
>>> 

Example 3. Apply with statement to open file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def printFileContent2(fileName):
    try:
        if(isFileExists("D:\\python\\txt\\" + fileName)==True):
            """ r stands for read """
            with open("D:\\python\\txt\\" + fileName, "r", encoding="utf-8") as data:
                for each_line in data:
                    print(each_line)
        
        else:
            print("查無檔案 : "+fileName)
    except IOError as err:
        print('IOError! ' + str(err))
    finally:
       if 'data' in locals():
        data.close()
    







No comments: