Home » Python

Python File close() Method with Example

Python File close() Method: Here, we are going to learn about the close() method, how to close an opened file in Python?
Submitted by IncludeHelp, on December 16, 2019

File close() Method

close() method is an inbuilt method in Python, it is used to flush and close the IO object (file). If we close a closed file it has no effect.

Syntax:

    file_object.close()

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is <class 'NoneType'>, it returns nothing.

Example 1:

# Python File close() Method with Example

# opening a file in write mode
f = open("Hello.txt", "w")
print("file opened...")
print(f) # prints file details

# closing the file 
f.close()
print("file closed...")

Output

file opened...
<_io.TextIOWrapper name='Hello.txt' mode='w' encoding='UTF-8'>
file closed...

Example 2:

# Python File close() Method with Example

# opening a file in write mode
f = open("Hello.txt", "w")
print("file opened...")

# closing the file
f.close()

# closing a closed file
f.close()
print("file closed...")

Output

file opened...
file closed...





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.