Skip to main content

Python Read and Write File

In this tutorial, you’ll learn how to read and write file in Python.

Program to Write to File

f = open("newtext.txt","w")
f.write("something to be write")
f.close()

Output:

this program will create a new file (if not exist) named as “newtext.txt” in the same directory where our program is located and write a line “something to be write”.

Program to Read File

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

Output:

something to be write

As we have seen the program, it is very easy to read and write into a file in python. In python we can work with two type of files Text files and Binary files. In this tutorial we are working with text file.

Python Read and Write File

Let’s understand above programs.

f = open("newtext.txt", "w")

open() is just a function to get the file object. It gets the file object and returns it to the f, we can name f as we want. using file object’s methods and attributes we can access the information that file have.

open() takes two arguments, first the file name (in our case, its “newtext.txt”) and second one is for access mode (optional).

Access Modes: it is an attribute of file object. Which tells, in which mode the file is opened.

There are 4 types of access modes.

  1. r: r stands for reading mode. If we open our file in this mode then we can only read the file’s information.
  2. w: w stands for writing mode. If we open our file in this mode then we can only write into the file, can’t read. If the file is not already exist then it will create new one, if it exists then it will delete all the previous content from the file and start writing from starting of the file.
  3. a: a stands for appending mode. It is same as writing mode but the difference is it will not delete the previous content of the file. It starts writing from the last of the file. In other words, it will append (concatenate) the new content with previous one.
  4. r+: special read and write mode. If we open the file using this mode then we can both read and write into the file.

Note: access mode is optional in open() method. By default the file will open into read mode (r).

Come to the next line of our program.

f.write("something to be write")

write() is a method of file object to write into the file. We will write in the parenthesis, what we want to write into the file (as shown above).

To read from the file:

print f.read()

read() is a method of file object to read the information stored in a file object. read() method read all the information from the given file object and returns it.

Last line in our program:

f.close()

close() is a method of file object to close the opened file. Which means we can’t access the file in our program now.

There are many other useful methods of the file objects like:-

read(int): if we pass any digit to the read() method then it will return same number of characters from the file object.

Example:

Let’s say we have a text file named as “newtext.txt” and “the crazy programmer” have written into it.

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

Output:

the crazy

readline(): it is used to read a single line (separated by enter key or \n ) from the file object.

Example:

Lets say our text file is look like this:

line number 1
line number 2
line number 3

f = open("newtext.txt", "r")
print f.readline()
f.close()

Output:

line number 1

f = open("newtext.txt", "r")
print f.readline()
print f.readline()
f.close()

Output:

line number 1
line number 2

readlines(): it reads all lines in the file object and return it as a List of lines.

Example:

f = open("newtext.txt", "r")
print f.readlines()
f.close()

Output:

[ ‘line number 1\n’ , ‘line number 2\n’ , ‘line number 3\n’]

If we want to print a specific line then:

f = open("newtext.txt", "r")
lines = f.readlines()
#to print the 3rd line 
print lines[2]
f.close()

Output:

line number 3

seek(int): it sets the position of reading and writing pointer. Using seek() method we can navigate to start or last of the file object.

This method takes 0,1,2 as argument.

  • 0 – takes pointer to the starting
  • 1 – current position of the pointer
  • 2 – takes pointer to the end

Example:

f = open("newtext.txt", "r")
print f.readline()
print f.readline()
f.seek(0)
print f.readline()
f.close()

Output:

line number 1
line number 2
line number 1

We can also use with statement to open the files for better indentation.

#to write into the file
with open("file.txt","w") as f:
f.write("example line")

It will create a new file named as “file.txt” and write “example line” into it.

Comment below if you have queries regarding above python file handling tutorial.

The post Python Read and Write File appeared first on The Crazy Programmer.



from The Crazy Programmer https://www.thecrazyprogrammer.com/2018/01/python-read-write-file.html

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan...

15 Web Design Trends to Watch in 2018

The modern world is full of extraordinary things that influence our imagination and mood. Our soul needs a perfect atmosphere and impressive spots. To apply such things in practice, we have submitted the list of the web trends that deserve your attention. Robert frost design analysis will meet all your wishes and expectations. Image Source Web Design Trends to Watch in 2018 1. More Organic Shapes Until this year, web design, as well as mobile design, were based on the right-angled and sharp-edged shapes. However, it seems that this year will bring some significant changes in the field of web design. The recent trends will offer the absolute rounded corners. In addition, the web design of 2018 will make the real things look like the cartoonish ones. 2.   Bold Minimalism Although some of you may think that this web design trend will not attract the Internet users. Indeed, the notion of minimalism is often associated with boredom and dullness. However, in this case, bold ...

R vs Python for Machine Learning

There are so many things to learn before to choose which language is good for Machine Learning. We will discuss each and everything about R as well as Python and the situation or problem in which situation we have to use which language. Let’s start Python and R are the two most Commonly used Programming Languages for Machine Learning and because of the popularity of both the languages Novice or you can say fresher are getting confused, whether they should choose R or Python language to commence their career in the Machine learning domain. Don’t worry guys through this article we will discuss R vs Python for Machine Learning. So, without exaggerating this article let’s get started. We will start it from the very Basics things or definitions. R vs Python for Machine Learning Introduction R is a programming language made by statisticians and data miners for statistical analysis and graphics supported by R foundation for statistical computing. R also provides high-quality graphics and...