Reading and writing to files in python
What Will I Learn?
This tutorial covers following topic:
- Files Objects
- Reading and writing to files
- Directories operations with os module
Requirements
- A PC/laptop with any Operating system such as Linux, Mac OSX, Windows OS
- Preinstalled Python
- Preinstalled Code Editors such as Atom, Sublime text or Pycharm IDE
Note: This tutorial is performed in Pycharm IDE in laptop with Ubuntu 17.1, 64 bit OS
Difficulty
Intermediate, anyone with basic programming knowledge of python or any other programming language can catch up this tutorial. I recommend learning basics of python programming before starting this tutorial. The links for previous tutorials are at the bottom of this tutorial.
Tutorial Contents
We will learn how to work with data files.
fileobject=open(filename,mode)
fileobject.close()
Above is the syntax to work with files. file object holds the value returned by the open function. open function mostly consists of two arguments: filename and mode. The filename is the name of the file which is going to be open. It is a string value. The mode is also a string value, which tells that in which way we are going to use the file. There are different modes in which we can use files in python. Some of them are discussed below:
- 'r' - used when we only need to read the file.
- 'w' - used when we only need to write to file.
- 'r+' - used when we need to both read and write to files.
- 'w+' - used when we need to write to files and read it.
- 'rb' - used when we need to open files to read only in binary format.
The close() closes the files after that we won't be able to use file object further.
Reading and writing files:
write() allows to write text or binary data to opened files.
# Opening a file
fileobject = open("newfile.txt", "w")
# writing to file
fileobject.write("Follow programminghub tutorials to learn python programming.\nLearn to code.\n Learning is great.\n");
# Closing opened file
fileobject.close()
We are creating file in the same directory of our project else we need to give path with filename. Output file after running above code is found here
read() allows reading text or binary data from opened files.
# Opening a file
fileobject = open("newfile.txt", "r+")
#reading 30 bytes from file
readlines = fileobject.read(30)
print(readlines)
# Closing opened file
fileobject.close()
We read the newfile.txt which we have created earlier and printed the read words.
Output:
Follow programminghub tutorial
With keyword:
We can also work with files using with keyword. with makes our code cleaner and it also handles exceptions. . Using with is almost equall to write try-finally blocks in code and we don't have to call close().
with open('newfile.txt') as nf:
readline = nf.read(30)
print(readline)
Output:
Follow programminghub tutorial
Working with multiple files:
Let us try to copy the texts from our newfile.txt to another file.
with open('newfile.txt', 'r') as nf:
with open('newfile2.txt', 'w') as nff:
for line in nf:
nff.write(line)
above line of code copys the text from newfile.txt to newfile2.txt. We do that by looping line from newfile.txt and writing it on newfile2.txt. The new files that this code creates is found here.
Renaming, removing files and making,deleting directories using os module:
First of all we need to import os module.
import os
os.rename(new file name, old file name) renames the file.
os.remove(file name) removes the file.
os.mkdir(dirname) creates new directory.
os.getcwd() gives current working directory.
os.rmdir(dirname) deletes the given directory.
import os
os.rename('newfile.txt','oldfile.txt' )
This code will change the name of our earlier created file from newfile.txt to oldfile.txt.
Try other above mentioned methods yourself. We will catch up in next tutorial of this series.
All above codes including previous tutorials codes are available in my Github repo. Click here to download
Now we are able to work with files in Python.
For more details please visit Python Docs.
Curriculum
Python tutorials for beginners : Part - I
Python tutorials for beginners : Part - II
Python tutorials for beginners : Part - III
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Thanks
Excellent tutorial
@mattboston Thanks
Hey @programminghub I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x