This week we learned about File IO. IO means input and output. So the content is basically about reading and writing file.
Before doing any operations on file, we need to open the file. The command is open(filename, mode). ‘filename’ need to include the path of file. There are two ways to show the path, absolute path and relative path. Absolute path sees the file from the global view while relative path shows the file from the position of present script. In relative path, we use ‘.’ to show the current directory the script is in and use ‘..’ to show the parent directory of current directory.
Mode is about how we open the file. Common mode are ‘r’, ‘w’ and ‘a’. ‘r’ means we open the file to read only. ‘w’ means we open the file for writing. ‘a’ is similar to ‘w’. The different between ‘a’ and ‘w’ is that ‘w’ will erase previous content of the file to write and ‘a’ just append to the tail of previous content.
An example of opening file is : afile = open(‘a.txt’,’r’) afile is the file object we get from opening file a.txt in the read mode.
After opening the file, we can begin to do operations on it. We learned reading file first. To read write, we must open the file in the ‘r’ mode. Function read() can get all contents of the file. Function readline() can read file line by line. Function readlines() can get all lines of the file and return a list.
To write to file, we use function write(astring) to implement that. Pass a string parameter to write() function, and the string will be written to file.
An example of reading file and writing file:
afile = open(‘a.txt’,’r’) #try to read all content of file a.txt to content content = afile.read() print(content) afile.close() afile = open(‘a.txt’,’w’) #erase all content in a.txt, and write "hellow world" to it afile.write(“hello world”) afile.close()