• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Python » Python File I/O: Read and Write to Files in Python
Next →
← Prev

Python File I/O: Read and Write to Files in Python

By Dinesh Thakur

In this tutorial, we will explore the print() function in detail in the Python Programming Language Standard Library. There are many built-In functions that you can use for various purposes.

One of these functions is a print() function. Those of the print() function is that it takes any data and the printed on the screen or any output device. We will take a simple example to show how to use the print() function to print a string data type on the screen.

#using print to printout string
print("This string is output to the screen!")
Output: This string is output to the screen!

As shown in this example, the function called the print() contains a data type. As you can see, this type was printed on the screen after this program was executed. Let’s take another example and using the value of a variable with the print() function.

#Adding string and variable to print()
x = 10
print("The value of x is", x)
Output: The value of x is", 10

Here in this example, we just created a variable called X, and we are saying 10 as an integer value for this X variable. Then the print() function has two terms here.

The first one is a data type, and it is the value of X inside the double quotes, or you can also use single quotes instead. This data type will be printed before the value of the X variable on the screen. We just separated them using come on inside the parentheses of the print() function, and the output should be looks like that the value of X is 10.

Also, there are built-In parameters for this print() function. And let show you how to use them in action with the print() function.

print(1, 3, 5, 7, 8)
print(1, 3, 5, 7, 8, sep="*")
print(1, 3, 5, 7, 8, sep="#", end="&")
Output:
1, 3, 5, 7, 8
1*3*5*7*8
1#3#5#7#8&

You can see now that two parameters for the print() function or the two arguments, the first one is the separator, and the second one is the and the zip parameter or the separate or parameter is used between the values.

And we’re not using the spirit or parameter. It defaults into a space character. As you can see, after all values are printed, then the parameter is printed, and it defaults into annualizing also. We’re not using the N parameter with the print function. It defaults into a new online.

We’ll be covering the following topics in this tutorial:

  • Formatting the output.
  • Opening and Closing Files

Formatting the output.

If you would like to format our output to make it look attractive in this case, you can use the format, method, or function. And this function is used with any string object.

Let’s do this by taking a simple example.

x = 10
y = 20
print("The value of x is {} and the value of y is {}".format(x,y))
Output: The value of x is 10 and the value of y is 20

In this program, the braces used as a placeholder, as the X variable’s value placed in the first curly braces’ position, and the Y variable placed in the second curly braces. You can also specify the order they represent by using a number or tuple index precisely as follows.

print("I like {0} and also {1}", format("Tea", "Milk"))
print("I like {1} and also {0}", format("Tea", "Milk"))
I like Tea and also Milk
I like Milk and also tea

You see, we got this resolved, and that is because he has index zero and index one, and there is another way, which is using the keyword arguments to format the string.

Let’s see that.

#Using keyword args to format
print("Hi {name}, {greet}", format(greet="Welcome", name="Thakur"))

This program has given us this output.

Hi Thakur, Welcome

Well, let’s talk about the input function.

You can take any type of data like string number list and so on using the input function.

number = input("Put your number: ")
Output: Put your number: 10

In this example, we have used the input() function to input from a user. We placed this input, it’s ten, and immediately after time, this value and the press, the enter button, this value was stored inside the variable called number. And now, the value of the number variable is ten.

You can also see that the entered value is ten is a string type, not a number string inside single quotes, as you can see. And to convert this into a number, you can use functions like and or offload.

Opening and Closing Files

Until now, you have been reading and writing according to a certain level. Now we will see how to manipulate data.

By default, Python provides the essential functions and methods necessary to manipulate files. You can manipulate files using a file object.

The open Function

You will learn here how to create, read and update files.

Syntax

file object = open(file_name [, access_mode][, buffering])

The most important function we will use with all operations here is the open function. The open function is working with files in the Python programming language. The open function takes two parameters or arguments. The first parameter or argument is called the name of the file—the file we want to create or update.

The second parameter or argument is called mode. There are four modes we use with files to open them. Let’s list all of them. First of all, "r" refers to read, and this is the default value. It opens a file for reading, and it returns an error if the file doesn’t exist. The second one is "a." It refers to what happened. It opens a file for an appending and also creates the file if it doesn’t exist.

The third one is "W,." refers to write. It opens a file for writing, and it creates the file if it doesn’t exist also.

And the last one is called "x." It refers to create the specified file, and it returns an error if the file exists.

Also, you can specify if the file should be handled as binary or text mode. There are two additional modes for referring to the text, and B refers to the binary mode. And this is the syntax to open a file for reading. It’s enough to specify the name of the file. Let’s create a text file so we can read it in Python. We will call this text file Demo. The text files ending with the extension, the text, and make sure to put that extension at the end of the file name.

To open the file, you can use the built-in function called open function. The open function returns a file object with a read method for reading the content of the file.

Let’s explain this in practice.

f = open("demo.txt, "r")
print(f.read())
Output: Hi,
Welcome to the demo.txt file.
Thanks.

Here we have the first function called open. This function has two parameters. As you can see, the first parameter is the name of the file we want to open and read, and the second parameter is the mode used for the reading process. And then, we use a function called Read, and this function is used to read the file, and we use it here with a variable equal to the open function. And you can see the result that this program gave us.

The whole file is called them, or the text has been read. So what can be done if we want to read certain parts of our file by default?

The Read method returns the whole text, but you can also specify how many characters you want to read. Let’s take a simple example to read in the first five characters of the demo text file.

There is also an essential function that we use to read files. This function is called the readline().

f = open("demo.txt, "r")
print(f.read(5))

You can read one line by using the readline() method. You can also use it multiple times to get lines from my file, each function for printing one line precisely as follows.

f = open("demo.txt, "r")
# print(f.read(5))
print(f.readline())
print(f.readline())
print(f.readline())

In this case, we have three readline() functions here. The first readline() function, in this case, is to read the first line from that immediate text file.

The second readline() function here is used to read the second line from the demo, the text file, etc. By looping through the file lines, you can read the whole file line by line, and you will get the same result that you also see.

f = open("demo.txt, "r")
# print(f.read(5))
for x in f:
print(x)

The Close Function

Now let’s talk about how to close files. It is an excellent practice always to close the file when you are done with it.

The close() method in the Python programming language is used to close the open file. A closed file cannot be read or written any more.

Any operation which requires that the file be opened where there is a value error after the file has been closed, calling the closed method more than once is allowed. Also, Python automatically closes a file when the reference object is reassigned to another file.

Now, let’s close that into the text file when you are finished with it.

f = open("demo.txt, "r")
print(f.read())
f.close()

The write() Function

Now it’s time to find out how to write inside a file to read to an existing file. You must add a parameter to the open function. There are two modes that we use for this purpose.

The first one is "a" it will happen to the end of the file, the second mode is called "W," it will override any existing content. Also, let’s create a new file, and we will call it main. And we use the right function to write the text inside the file after we created it.

f = open("main.txt", "a")
f.write("Another file is created and we are writing to it!")
f.close()

At first, we created a file called main, as you can see, and we used the mode called "a," and then the right function is to write the text you see inside the file. Another file is created, and we are writing to its string. And we closed the file after that. And to read the text, which we created and written inside them in the text file, you can use the read function for that purpose, just like what we are going to do.

f = open("main.txt", "r")
print(f.read())

As you can see in this case, we used the "r" mode.

To read the file that we created and the read inside it, if you want to create a file, you can use one of the three modes.

To create a new file in the Python programming language, you can use your open method with one of the following parameters.

f = open("file.txt", "x")
f = open("new.txt", "w")

You’ll also like:

  1. What is Files & Types of Files? Types of File Operations.
  2. Write A C++ Program To Read And Write The Library Data By Using Structure.
  3. Write a C++ program to read and write the student data by using structure.
  4. Write a Program to Copy a File using File Handling Functions.
  5. Write a Program to Count Vowels in a File Using File Handling
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Python

Python Tutorials

  • Python - Home
  • Python - Features
  • Python - Installation
  • Python - Hello World
  • Python - Operators Types
  • Python - Data Types
  • Python - Variable Type
  • Python - Switch Case
  • Python - Line Structure
  • Python - String Variables
  • Python - Condition Statement
  • Python - if else Statement
  • Python - for-loop
  • Python - while loop
  • Python - Command Line
  • Python - Regular Expression

Python Collections Data Types

  • Python - List
  • Python - Sets
  • Python - Tuples
  • Python - Dictionary

Python Functions

  • Python - Functions
  • Python - String Functions
  • Python - Lambda Function
  • Python - map() Function

Python Object Oriented

  • Python - Oops Concepts
  • Python - File Handling
  • Python - Exception Handling
  • Python - Multithreading
  • Python - File I/O

Python Data Structure

  • Python - Linked List
  • Python - Bubble Sort
  • Python - Selection Sort
  • Python - Linear Search
  • Python - Binary Search

Python Programs

  • Python - Armstrong Number
  • Python - Leap Year Program
  • Python - Fibonacci Series
  • Python - Factorial Program

Other Links

  • Python - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2023. All Rights Reserved.