Saturday 24 July 2021

Python crash course part 8: file input and output

In today's post I'll provide some short samples of working with files in Python.

Let's begin with text files and let's create a file first.

# !/usr/bin/python3

def main():
    # create a file
    my_file = open('newfile.txt''w')
    # write some data to it:
    my_file.write("Anakin Skywalker")
    my_file.close()

    # contents of the file: 
    # Anakin Skywalker

if __name__ == "__main__":
    main()

The result of running this code is creating a file newfile.txt with content: Anakin Skywalker

'w' means that the we will write to the file, and if that file exits, it will be overwritten. Remember to call .close() on the file object after opening and doing some operation on it.

Let's extend our program, by calling the similar code again:

# !/usr/bin/python3

def main():
    # create a file
    my_file = open('newfile.txt''w')
    # write some data to it:
    my_file.write("Anakin Skywalker")
    my_file.close()

    # contents of the file: 
    # Anakin Skywalker

    # opening it again
    my_file = open('newfile.txt''w')
    my_file.write("Darth Vader")
    my_file.close()

    # contents of the file: 
    # Dath Vader

if __name__ == "__main__":
    main()

As the 'w' mode makes the write call overwrite the file contents, it will be just Darth Vader  after the call. What if we want to actually add something to the file, not deleting it contents?

That's what 'a' (append) mode is for:

# !/usr/bin/python3

def main():
    # create a file
    my_file = open('newfile.txt''w')
    # write some data to it:
    my_file.write("Anakin Skywalker")
    my_file.close()

    # contents of the file: 
    # Anakin Skywalker

    # opening it again
    my_file = open('newfile.txt''w')
    my_file.write("Darth Vader")
    my_file.close()

    # contents of the file: 
    # Dath Vader
    my_file = open('newFile.txt','a')
    my_file.write("\nLuke Skywalker")
    my_file.close()
    # contents:
    # Darth Vader
    # Luke Skywalker


if __name__ == "__main__":
    main()

Because 'a' mode is used instead of 'w', \nLuke Skywalker is added (appended) to the existing file. The \n before the text itself in the third write call is a new line sign between the first and second line. The contents of the file become:

Darth Vader
Luke Skywalker

We know how to write to file, but how to read from it? This is what open() with 'r' (read) parameter is for. We use it like this:

# !/usr/bin/python3

def main():
    # create a file
    my_file = open('newfile.txt''w')
    # write some data to it:
    my_file.write("Anakin Skywalker")
    my_file.close()

    # contents of the file: 
    # Anakin Skywalker

    # opening it again
    my_file = open('newfile.txt''w')
    my_file.write("Darth Vader")
    my_file.close()

    # contents of the file: 
    # Dath Vader
    my_file = open('newFile.txt','a')
    my_file.write("\nLuke Skywalker")
    my_file.close()
    # contents:
    # Darth Vader
    # Luke Skywalker
    
    to_read = open('newFile.txt','r')
    file_contents = to_read.readlines()
    for val in file_contents:
        print(val)

    #result:
    #Darth Vader
    #
    #Luke Skywalker   

if __name__ == "__main__":
    main()

The code above creates the file, adds 2 lines (Darth Vader and Luke Skywalker) to it, and the reads lines from the file, puts them in file_contents variable (list) and prints them to console.

The execution result is therefore:

Darth Vader

Luke Skywalker

As you can see, there is something strange with this result: there is an empty line between Darth and Luke, which is not in the file. That's because print(val) adds a new line character after the text it prints, and there is already one new line between Darth Vader and Luke Skywalker in the file.

In order to fix it, we can use an overloaded version of the print() function: print(val,end=''), which specifies that in the end of the text it should use an empty character instead of new line:

# !/usr/bin/python3

def main():
    # create a file
    my_file = open('newfile.txt''w')
    # write some data to it:
    my_file.write("Anakin Skywalker")
    my_file.close()

    # contents of the file: 
    # Anakin Skywalker

    # opening it again
    my_file = open('newfile.txt''w')
    my_file.write("Darth Vader")
    my_file.close()

    # contents of the file: 
    # Dath Vader
    my_file = open('newFile.txt','a')
    my_file.write("\nLuke Skywalker")
    my_file.close()
    # contents:
    # Darth Vader
    # Luke Skywalker

    to_read = open('newFile.txt','r')
    file_contents = to_read.readlines()
    for val in file_contents:
        print(val,end='')

if __name__ == "__main__":
    main()

The execution of the code above finally results in:

Darth Vader
Luke Skywalker

... which are contents of the file created above :).

We've covered text files - what about binary files? Here we're going to focus on reading from such file (let's be honest - writing to binary file is not very commond situation).

And reading from binary files is easy: we have to set 'rb' (read binary) instead of just 'r' (read) as our file open mode, and then we can read, for instance, a few bytes from the file. Those bytes become bytes array. So if we have, for instance, wav file (which should begin with letters RIFF in ASCII form), the reading of a first fragment of such file would look like this:

# !/usr/bin/python3

def main():

    binary_file = open('sound.wav','rb')
    bytes = binary_file.read(4#bytes
    print(bytes[0])
    print(bytes[1])
    print(bytes[2])
    print(bytes[3])
    
    print(str(bytes))

if __name__ == "__main__":
    main()

Which results in:

82
73
70
70
b'RIFF'

(which means it looks like some wav file indeed :) )

No comments:

Post a Comment

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means cre...