file properties and methods

1. file.closed – Is the file door shut?

Think of a file like a door. file.closed tells you if the door is open or closed.

python

# Open the file (open the door)
f = open("test.txt", "w")
f.write("Hello!")

print(f.closed)  # Output: False (door is open)

# Close the file (close the door)
f.close()

print(f.closed)  # Output: True (door is closed)

2. file.mode – What can you do with the file?

This tells you how the file was opened – for reading, writing, or both.

python

# Open for reading
f1 = open("test.txt", "r")
print(f1.mode)  # Output: r (read only)
f1.close()

# Open for writing  
f2 = open("test.txt", "w")
print(f2.mode)  # Output: w (write only)
f2.close()

# Open for reading and writing
f3 = open("test.txt", "r+")
print(f3.mode)  # Output: r+ (read and write)
f3.close()

3. file.name – What’s the file’s name?

This simply tells you the name of the file you’re working with.

python

# Open a file
f = open("my_data.txt", "w")

print(f.name)  # Output: my_data.txt

f.write("Some data")
f.close()

Simple Example Showing All Three:

python

# Create and work with a file
file = open("diary.txt", "w")  # Open for writing

print("File name:", file.name)    # diary.txt
print("File mode:", file.mode)    # w
print("Is closed?", file.closed)  # False

file.write("Today was a good day.")
file.close()

print("Is closed now?", file.closed)  # True

The Easiest Way: Using with

The best practice is to use with – it automatically closes the file for you!

python

with open("story.txt", "w") as file:
    file.write("Once upon a time...")
    print("Mode:", file.mode)   # w
    print("Name:", file.name)   # story.txt
    print("Closed?", file.closed)  # False (still open inside the block)

# Outside the block, the file is automatically closed
print("Closed now?", file.closed)  # True

Simple Summary:

  • .closed → Is the file open or closed? (True/False)
  • .mode → How was it opened? (r/w/a)
  • .name → What’s the file called?

These are just simple properties of the file object you’re working with!

1. file.close()

Closes the file to free up resources.

python

# Manual way (easy to forget to close!)
f = open("test.txt", "w")
f.write("Hello World")
f.close()  # Don't forget this!

# Better way using 'with' (automatically closes)
with open("test.txt", "w") as f:
    f.write("Hello World")
# File automatically closes here

2. file.read(size)

Reads content from the file.

python

with open("test.txt", "w") as f:
    f.write("Hello World, this is Python!")

with open("test.txt", "r") as f:
    print(f.read(5))   # Reads first 5 characters: "Hello"
    print(f.read(6))   # Reads next 6 characters: " World"
    print(f.read())    # Reads the rest: ", this is Python!"

3. file.readline()

Reads one line at a time.

python

with open("story.txt", "w") as f:
    f.write("Line 1\nLine 2\nLine 3")

with open("story.txt", "r") as f:
    print(f.readline())  # "Line 1\n"
    print(f.readline())  # "Line 2\n"
    print(f.readline())  # "Line 3"

4. file.readlines()

Reads all lines into a list.

python

with open("story.txt", "w") as f:
    f.write("First line\nSecond line\nThird line")

with open("story.txt", "r") as f:
    lines = f.readlines()
    print(lines)  # ['First line\n', 'Second line\n', 'Third line']

5. file.write(string)

Writes text to the file.

python

with open("output.txt", "w") as f:
    chars_written = f.write("Hello Python!")
    print(f"Wrote {chars_written} characters")  # Wrote 13 characters

6. file.writelines(list)

Writes a list of strings to the file.

python

lines_to_write = ["Line 1\n", "Line 2\n", "Line 3"]

with open("multi_lines.txt", "w") as f:
    f.writelines(lines_to_write)
# File contains: Line 1
#                Line 2
#                Line 3

7. file.seek(offset)

Moves the file pointer to a specific position.

python

with open("test.txt", "w") as f:
    f.write("0123456789")

with open("test.txt", "r") as f:
    print(f.read(3))  # "012"
    f.seek(0)         # Go back to start
    print(f.read(3))  # "012" again
    f.seek(5)         # Jump to position 5
    print(f.read(3))  # "567"

8. file.tell()

Tells you the current position in the file.

python

with open("test.txt", "w") as f:
    f.write("Hello World")

with open("test.txt", "r") as f:
    print(f.tell())  # 0 (start)
    f.read(5)
    print(f.tell())  # 5 (after reading 5 characters)
    f.read(3)
    print(f.tell())  # 8 (after reading 3 more)

Complete Example Showing All Methods:

python

# Create a file
with open("example.txt", "w") as f:
    f.write("Line One\nLine Two\nLine Three")

# Read and manipulate the file
with open("example.txt", "r+") as f:  # r+ = read and write
    print("Initial position:", f.tell())  # 0
    
    # Read first line
    first_line = f.readline()
    print("First line:", first_line.strip())
    print("Position after readline:", f.tell())  # 9
    
    # Jump to beginning
    f.seek(0)
    print("Position after seek(0):", f.tell())  # 0
    
    # Read all content
    content = f.read()
    print("Full content:", content)
    
    # Go to end and add new text
    f.seek(0, 2)  # 2 = end of file
    f.write("\nLine Four")
    
    # Check final position
    print("Final position:", f.tell())

Simple Summary:

  • close() – Shut the file when done
  • read() – Read content from file
  • readline() – Read one line
  • readlines() – Read all lines as a list
  • write() – Write text to file
  • writelines() – Write a list of lines
  • seek() – Move to a specific position
  • tell() – Check current position

Always use with statement – it automatically handles closing the file for you!

Similar Posts

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

  • Variable Length Keyword Arguments in Python

    Variable Length Keyword Arguments in Python Variable length keyword arguments allow a function to accept any number of keyword arguments. This is done using the **kwargs syntax. Syntax python def function_name(**kwargs): # function body # kwargs becomes a dictionary containing all keyword arguments Simple Examples Example 1: Basic **kwargs python def print_info(**kwargs): print(“Information received:”, kwargs) print(“Type of…

  • String Alignment and Padding in Python

    String Alignment and Padding in Python In Python, you can align and pad strings to make them visually consistent in output. The main methods used for this are: 1. str.ljust(width, fillchar) Left-aligns the string and fills remaining space with a specified character (default: space). Syntax: python string.ljust(width, fillchar=’ ‘) Example: python text = “Python” print(text.ljust(10)) #…

  • Classes and Objects in Python

    Classes and Objects in Python What are Classes and Objects? In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). Real-world Analogy Think of a class as a “cookie cutter” and objects as the “cookies” made from it. The cookie cutter defines the shape, and each cookie is an instance of that shape. 1. Using type() function The type() function returns…

  • Combined Character Classes

    Combined Character Classes Explained with Examples 1. [a-zA-Z0-9_] – Word characters (same as \w) Description: Matches any letter (lowercase or uppercase), any digit, or underscore Example 1: Extract all word characters from text python import re text = “User_name123! Email: test@example.com” result = re.findall(r'[a-zA-Z0-9_]’, text) print(result) # [‘U’, ‘s’, ‘e’, ‘r’, ‘_’, ‘n’, ‘a’, ‘m’, ‘e’, ‘1’, ‘2’,…

  • Predefined Character Classes

    Predefined Character Classes Pattern Description Equivalent . Matches any character except newline \d Matches any digit [0-9] \D Matches any non-digit [^0-9] \w Matches any word character [a-zA-Z0-9_] \W Matches any non-word character [^a-zA-Z0-9_] \s Matches any whitespace character [ \t\n\r\f\v] \S Matches any non-whitespace character [^ \t\n\r\f\v] 1. Literal Character a Matches: The exact character…

Leave a Reply

Your email address will not be published. Required fields are marked *