# File IO 檔案讀寫¶

• 這邊介紹python 內建的開啟檔案與檔案讀寫指令，在處理文字為主的檔案時比較方便
• 如果需要讀取的資料是排列整齊的大量數值資料，NumPy提供更方便的檔案讀寫功能，會在NumPyFileIO單元介紹
• Here we will introduce the file open, Input, and Output functions built-in in Python. These functions are usefull when processing text files with strings.
• If the data files contains a large amount of numbers in well-organized format, the NumPy toolbox provides even more handy functions for IO, and we will introduce those in the NumPyFileIO topic

# python 內建的讀檔指令¶

Before you read or write a file using the python built-in read/write function, you need to "open" the file first.

## open()打開檔案¶

• r : for both reading only. 只讀檔，檔案要先存在，從頭開始讀
• r+ : for both reading and writing. 可讀可寫，檔案要先存在，從頭開始讀。
• w : for writing only. Overwrites existing file; if nonexisting, creates a new file. 只可寫出，從頭覆蓋既有檔案，檔案如果不存在就新增。
• w+ : for both writing and reading. Overwrites existing file; if nonexisting, creates a new file.可讀可寫，從頭覆蓋既有檔案，檔案如果不存在就新增。
• a : for appending at the end of the file if the file exists. If nonexisting, creates a new file. 接續既有檔案寫出，檔案如果不存在就新增。
• a+ : for both appending and reading at the end of the file if the file exists. If nonexisting, creates a new file. 接續既有檔案寫出與讀取，檔案如果不存在就新增。

### The file Object Attributes¶

Once a file is opened and you have one file object, you can get various information related to that file.

Here is a list of all attributes related to file object:

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.

## Example of opening a file, and checking its status¶

In [1]:
# Open a file
fo = open("foo.txt", "wb")              # Open for writing in binary format. Overwrites existing file.
print("Name of the file: ", fo.name)    # Let's check if the file name is correct
print("Opening mode : ", fo.mode)       # Check the read/write/binary mode status
print("Closed or not : ", fo.closed)    # Check the open/close status

Name of the file:  foo.txt
Opening mode :  wb
Closed or not :  False


## close() 關閉檔案¶

The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.

Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

### Syntax¶

fileObject.close()

### Example¶

In [2]:
# Open a file
fo = open("foo.txt", "wb")
print("Closed or not : ", fo.closed)    # Check the open/close status

# Close opend file
fo.close()
print("Closed or not : ", fo.closed)    # Check the open/close status again

Closed or not :  False
Closed or not :  True


## write() 輸出到檔案¶

The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.<br>

The write() method does not add a newline character ('\n') to the end of the string automatically. In order to output multiple lines, add a '\n' character at the position of the end of each line.

### Syntax¶

fileObject.write(string)

### Example¶

In [3]:
# Open a file
fo = open("foo.txt", "w")   # open for writing only
fo.write("This is the first output.")  # output string to the file.
# As no \n is included at the end of the string ,
# the next __write()__ will continue to output to the same line.

fo.write("This is the second output.\n")  # Continue the first line.
# A \n is included at the end. The next __write()__ will start a new line

fo.write("Python is a great language.\nYeah its great!!\n")  #write two new lines to the file

# Close opend file
fo.close()


The read() method reads a string from an open file. It is important to note that Python strings can have binary data, not only text data.

## Example¶

In [4]:
fo = open("foo.txt", "r")  # open for readingly only; read from the beginning
print(A)
print(B)

This is
the first


## Example¶

In [25]:
fo = open("foo.txt", "r")  # open for reading only; read from the beginning
print(A)

B=fo.readlines() # read the rest of the file (2nd~3rd lines) as a python list
print(len(B))    # checking the size of the list
print(B)         # the elements are separated by'\n' in the string
print(B[1])      # the second element in the list

This is the first output.This is the second output.

2
['Python is a great language.\n', 'Yeah its great!!\n']
Yeah its great!!



### Syntax （語法）¶

var.split(delimiter, number of element) 根據分隔符號將var字串區分成不同的element

## Example¶

In [35]:
fo = open("foo.txt", "r")  # open for readingly only; read from the beginning
print(A)
As=A.split(' ')
print(As)


This is the first output.This is the second output.