0% found this document useful (0 votes)
5 views10 pages

File Object.doc

The document provides an overview of file handling in Python, detailing how to open, read, write, and close files using the built-in open() function and various file modes. It explains different methods for reading files, such as read(), readline(), and looping through file objects, as well as writing to files and the importance of closing them. Additionally, it introduces the use of the 'with' statement for better file management and outlines built-in methods and attributes related to file objects.

Uploaded by

rj0110865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views10 pages

File Object.doc

The document provides an overview of file handling in Python, detailing how to open, read, write, and close files using the built-in open() function and various file modes. It explains different methods for reading files, such as read(), readline(), and looping through file objects, as well as writing to files and the importance of closing them. Additionally, it introduces the use of the 'with' statement for better file management and outlines built-in methods and attributes related to file objects.

Uploaded by

rj0110865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

In Python, The open() function opens a file and returns a file object.

The file
objects contain methods and attributes which latter can be used to retrieve
information or manipulate the file you opened.
File Operations
The file is a named location on the disk to store related information, as the file
is having some name and location, it is stored in the hard disk. In Python, file
operation is performed in the following order -
 Opening a file.
 Read or Write operation.
 Closing a file.

Opening a File Using the 'open()' function


To open a file for both reading and writing, we must use the built-
in open() function. The open() function uses two arguments. First is the name
of the file and second is the mode (reading or, writing). The syntax to open a file
object in Python is -
File_obj = open("filename", "mode")
Python File Modes
Once a file is opened, the file mode can be specified. For example, If we want
to add append mode "a", to the file, write "w" or read "r". In addition, we
have the option to open the file in binary mode or text format. Following are the
different modes supported in the open() function -

Mode Description

‘r’ Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates
‘w’
the file if it exists.

Open a file for exclusive creation. If the file already exists, the operation
‘x’
fails.

‘a’ Open for appending at the end of the file without truncating it. Creates a
Mode Description

new file if it does not exist.

‘t’ Open in text mode. (default)

‘b’ Open in binary mode.

‘+’ Open a file for updating (reading and writing)

Create a text file


Let’s create a simple text file in Python using any text editor. In the following
example, a new file is created in our current working directory, and on opening
the newly created file.
# Create a text file named "textfile.txt" in your current working directory
f = open("textfile.txt", "w")
# above will create a file named textfile.txt in your default directory
f.write("Hello, Python")

f.write("\nThis is our first line")

f.write("\nThis is our second line")

f.write("\nWhy writing more?, Because we can :)")

f.close()
Output
Reading a Text file
There are various ways to read a text file in Python, some of them are as follows
below.
 Extracting all characters of a string
 Reading certain numbers of character
 Reading a file line by line
 Looping over a file object
 Splitting Lines in a Text File
Extracting all characters of a string
In case you want to extract a string that contains all characters in the file. We
can use the following method:
file.read()
Example
f = open("textfile.txt", "r")
f.read()
Output
'Hello, Python\nThis is our first line\nThis is our second line\nWhy writing
more?, Because we can :)'
Reading certain numbers of character
If you want to read a certain number of characters in the string from a file, we
can use the method as shown below -
f = open("textfile.txt", "r")
print(f.read(13))
Output
Hello, Python
Reading a file line by line
However, if you want to read a file line by line then you can use the readline()
function.
Example
f = open("textfile.txt", "r")
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
Output
Hello, Python

This is our first line

This is our second line

Why writing more?, Because we can :)


Looping over a file object
In case you want to read or return all the lines from the file in the most
structured and efficient way, we can use the loop-over method.
f = open("textfile.txt", "r")
for line in f:
print(line)
Output
Hello, Python

This is our first line


This is our second line

Why writing more?, Because we can :)


Splitting Lines in a Text File
We can split the lines taken from a text file using the Python split() function. We
can split our text using any character of your choice it can either be a space
character colon or something else.
with open("textfile.txt", "r") as f:
data = f.readlines()
for line in data:
words = line.split()
print(words)
Output
['There', 'are', 'tons', 'to', 'reason', 'to', "'fall", 'in', 'love', 'with', "PYTHON'"]
['See,', 'i', 'have', 'added', 'one', 'more', 'line', ':).']
['Hello,', 'Python-Here', 'i', 'come', 'once', 'again!']

Writing to a file
Writing to a file is simple, you just need to open the file and pass on the text you
want to write to a file. We can use the open() method to append data to an
existing file. Use the EOL character to start a new line after you write data to
the file.
Example
f = open("textfile.txt", "w")
f.write("There are tons to reason to 'fall in love with PYTHON'")
f.write("\nSee, i have added one more line :).")

f.close()
f = open("textfile.txt", "r")
for line in f:
print(line)
Output
There are tons to reason to 'fall in love with PYTHON'
See, i have added one more line :).
Closing a file
Once you’re done working on a file, you have to use the f.close() command to
end things. With this, we’ve closed the file completely, terminating all the
resources in use and freeing them up for the system to use elsewhere.
Example
f = open("textfile.txt", "r")
f.close()
f.readlines()
Output
Once the file is closed, any attempt to use the file object will through an error.
Traceback (most recent call last):
File "<pyshell#95>", line 1, in <module>
f.readlines()
ValueError: I/O operation on closed file.
Using "with" Statement
The with statement can be used with file objects. Using the two (with statement
& file objects) we get, much cleaner syntax and exception handling in our
program.
Another advantage is that any files opened will be closed automatically once we
are done with file operations
Syntax
with open(“filename”) as file:
Example:
In this example, the file is automatically closed at the end of the with block, so
there is no need to call the close() method explicitly.
Open Compiler
with open("example.txt", "w") as file:
file.write("This is an example using the with statement.")
print ("File closed successfully!!")
Output
File closed successfully!!

File Built-in Methods


Python supports file handling and allows users to handle files i.e., to read and
write files, along with many other file handling options, to operate on files. For
this, python provides following built–in functions, those are
 close()
 read()
 readline()
 write()
 writelines()
 tell()
 seek()
☞ close()
The close() method used to close the currently opened file, after which no more
writing or Reading can be done.
Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to close
a file.
close()
The close() method used to close the currently opened file, after which no more
writing or Reading can be done.
Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to close
a file.
Syntax:
Fileobject.close()

Example:
f = open("myfile.txt", "r")
f.close()
read()
The read () method is used to read the content from file. To read a file in
Python, we must open the file in reading mode.
Syntax:
Fileobject.read([size])
Where ‘size’ specifies number of bytes to be read.
myfile.txt
function open() to open a file.
method read() to read a file.
readline()
Python facilitates us to read the file line by line by using a function readline().
The readline() method reads the lines of the file from the beginning, i.e., if we
use the readline() method two times, then we can get the first two lines of the
file.
Syntax:
Fileobject.readline()

myfile.txt
function open() to open a file.
method read() to read a file.
write()
The write () method is used to write the content into file. To write some text to a
file, we need to open the file using the open method with one of the following
access modes.
w: It will overwrite the file if any file exists. The file pointer point at the
beginning of the file in this mode.
Syntax:
Fileobject.write(content)

myfile.txt
function open() to open a file.
method read() to read a file.
It will append the existing file. The file pointer point at the end of the file.
myfile.txt
function open() to open a file.
method read() to read a file.
File Positions
Methods that set or modify the current position within the file
☞ tell()
The tell() method returns the current file position in a file stream. You can
change the current file position with the seek() method.
Syntax:
Fileobject.tell()

myfile.txt
function open() to open a file.
method read() to read a file.
seek()
The seek() method sets and returns the current file position in a file stream.
Syntax:
Fileobject.seek(offset)

myfile.txt
function open() to open a file.
method read() to read a file.
Example:
f = open("myfile.txt", "r")
print(f.seek(9))
print(f.read())
f.close();
First We moved 9bytes with seek function and then started reading
File Built-in Attributes
Python Supports following built-in attributes, those are
 file.name - returns the name of the file which is already opened.
 file.mode - returns the access mode of opened file.
 file.closed - returns true, if the file closed, otherwise false.
Example:
f = open ("myfile.txt", "r")
print(f.name)
print(f.mode)
print(f.closed)
f.close()
print(f.closed)

Output:
myfile.txt
r
False
True

You might also like