Python Unleashed: Unlock the Potential of Programming — File Input and Output

Woody
5 min readJan 17, 2023

Chapter 7

Photo by Christina @ wocintechchat.com on Unsplash

Introduction

File Input and Output (I/O) is a way for a program to read data from a file or write data to a file. In Python, you can use the built-in open() function to work with files. The open() function takes a filename as its first argument and a mode as its second argument. The mode specifies whether the file should be opened for reading ('r'), writing ('w'), or appending ('a').

Here is an example of how to open a file for reading:

f = open('myfile.txt', 'r')

And here is an example of how to open a file for writing:

f = open('myfile.txt', 'w')

When you’re done working with a file, you should close it using the close() method:

f.close()

It’s worth mentioning that you can use the with statement to open files, this will take care of closing the file after you're done using it.

with open('myfile.txt', 'r') as f:
# do something with the file

Reading from Files

Once a file is opened for reading, you can read its contents using the read() method. The read() method reads the entire contents of the file and…

--

--

Woody
Woody

Written by Woody

Developer and technology enthusiast new to Medium writing.

No responses yet