Py20: File Input and Output

Data displayed in console are not saved and cannot be retrieved once the program is closed. To save the data, it have to be stored inside of a file. This will make data accessible after the program is terminated.

Open a file

The first step before using file is to open the file.

object = open(filename, mode)

the filename is a string that specifies the name of the file to open.

mode to which mode to use to the opened file.

  • r - to open the file for reading. this is the default mode.
  • w - to open a file for writing. If the file doesn't exist, a new file with the given file name is created. If the file exists, it will be truncated.
  • a - to open a file for writing in append mode. If the file doesn't exist, a new file with the given file name is created.
myfile = open("demo.txt", 'r')

if myfile:
    print("The file is opened")

Output

The file is opened

Reading file

The following examples will be using the text file with the file name fruits.txt

apple
pen
pineapple
pie

To read the file we use the read() function..

myfile = open("fruits.txt", 'r')

if myfile:
    lines = myfile.read()

    print(lines)

Output

apple
pen
pineapple
pie

To read a single line we use the readline() function.

line = myfile.readline()

print(line)

Output

apple

Using readlines() function we can read multiple lines from the file. It returns list of lines.

lines = myfile.readlines()

for line in lines:
	print(line)

Output

['apple\n', 'pen\n', 'pineapple\n', 'pie']

Writing file

Open a file with mode 'w'. Use the write() function to write data to the file. If the file don't exist, a new file will automatically created.

Example

myfile = open("cars.txt", 'w')

myfile.write("Honda\n")
myfile.write("BMW\n")
myfile.write("Suzuki\n")

myfile.close()

Output (cars.txt)

Honda
BMW
Suzuki

Append file

When we open a file with 'w' access mode, if the file is already exist, it overwrites the content. Existing content will be lost. To write to a file without truncating the file, we need to specify 'a' access mode. New data will be appended at the end of file.

For example, we already has data saved in cars.txt from previous example. We will append new data here.

myfile = open("cars.txt", 'a')

myfile.write("Toyota\n")
myfile.write("Mercedes\n")
myfile.write("Chevrolet\n")

myfile.close()

Output (cars.txt)

Honda
BMW
Suzuki
Toyota
Mercedes
Chevrolet

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net