Intensity Coding
  • HOME
  • TUTORIALS
    • Python
    • Natural Language Processing
    • Generative AI
  • ABOUT US
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms and Conditions
    • Disclaimer

Python

Python File Handling

Python
Python
  • Introduction To Python
  • Write Your First Python Program
  • Indentation And Comments in Python
  • Variables in Python
  • Data Types in Python
  • Booleans and Number in Python
  • Operators in Python
  • Mutable Vs Immutable Objects And Collection in Python
  • Python String
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Control Statements
  • Python Functions
  • Python Lambda Functions
  • Python Exception Handling
  • Python File Handling
  • Python Package and PIP
  • Python Modules
  • Python Keywords
  • Python Built In Method
  • Python Regular Expressions (RegEx)
  • Python JSON
  • Python Datetime

Python File Handling¶

  • File handling is a crucial aspect of developing data-driven applications.
  • Python provides several functions to create, read, write, and delete files.

Python File open() Function¶

  • Python’s open() function is the foundation for file operations. It accepts two primary parameters:
filename: The name or path of the file to open.
mode: The operation mode (e.g., read, write).

Basic Syntax¶

In [ ]:
# Open a file in read mode
file = open("filename.txt")

# Equivalent to:
file = open("filename.txt", "rt")
Note: Ensure the file exists before opening it in "r" mode, otherwise Python will raise an error.

File Open Modes in Python¶

Mode Description
"r" Read-only. Default mode. Error if file doesn't exist.
"a" Append mode. Creates file if it doesn't exist.
"w" Write mode. Overwrites file if it exists, creates if not.
"x" Exclusive creation. Error if file already exists.

Text vs Binary Mode¶

Mode Description
"t" Text mode (default). Use for plain text files.
"b" Binary mode. Use for binary files like images or models.

File Modes with Variations¶

Mode Purpose
r Read text. Error if file doesn't exist.
rb Read binary. Error if file doesn't exist.
r+ Read and write text. Error if file doesn't exist.
rb+ Read and write binary. Error if file doesn't exist.
w Write text. Overwrites or creates a new file.
wb Write binary. Overwrites or creates a new file.
w+ Read and write text. Overwrites or creates a new file.
wb+ Read and write binary. Overwrites or creates a new file.
a Append text. Creates file if not present. Inserts data at end of the file.
ab Append binary. Creates file if not present. Inserts data at end of the file.
a+ Read and append text. Creates file if not present. Inserts data at end of the file.
ab+ Read and append binary. Creates file if not present. Inserts data at end of the file.
Default mode is "rt": read + text.

File Object Attributes¶

  • Once you open a file using open(), Python returns a file object. You can access several useful attributes:
Attribute Description
file.name Returns the name/path of the file.
file.mode Indicates the mode in which the file was opened.
file.closed Boolean indicating if the file is closed.

Example¶

In [ ]:
# Open a file to write binary data
file_example = open("filename.txt", "wb")

# Display file information
print("Name of the file: ", file_example.name)      # Output: filename.txt
print("Closed or not : ", file_example.closed)      # Output: False (file is open)
print("Opening mode : ", file_example.mode)         # Output: wb (write in binary mode)

# Always remember to close the file
file_example.close()
Name of the file:  filename.txt
Closed or not :  False
Opening mode :  wb
Best Practice: Always close your files using file.close() or use the with statement for automatic handling. In some cases, due to buffering, changes made to a file may not show until you close the file.

Python File Read¶

  • Let’s assume we have a file named info.txt in the same directory with the following content:
cat
dog
bird
cat

Opening a File Using open()¶

  • Python’s built-in open() function returns a file object that can be read using methods like read(), readline(), or loops.
In [ ]:
# Open the file in read mode
file = open("info.txt", "r")

# Read the entire content of the file
print(file.read())

# Always close the file after reading
file.close()

# Output:
# cat
# dog
# bird
# cat
cat
dog
bird
cat

Reading from a Specific File Path¶

  • If your file is located elsewhere (e.g., inside a folder)
In [ ]:
# Specify full path if the file is not in the same folder
file = open("/content/data/info.txt", "r")
print(file.read())
file.close()
cat
dog
bird
cat

Reading Specific Number of Characters¶

  • Use the read(n) method to read only a defined number of characters.
In [ ]:
# Read only the first 10 characters from the file
file = open("info.txt", "r")
print(file.read(3))  # Output: cat
file.close()
cat

Reading Lines One at a Time¶

  • Use the readline() method to read a single line.
In [ ]:
# Read the first line of the file
file = open("info.txt", "r")
print(file.readline())  # Output: cat
file.close()
cat

  • You can call readline() multiple times to read multiple lines.
In [ ]:
file = open("info.txt", "r")
print(file.readline())  # Output: Model: cat
print(file.readline())  # Output: dog
file.close()
cat

dog

Reading All Lines Using a Loop¶

  • You can iterate through the file line by line using a for loop
In [ ]:
# Read each line in the file using a loop
file = open("info.txt", "r")

for line in file:
    print("Line:", line.strip())  # strip() removes extra newline characters

file.close()

# Output:
# Line: cat
# Line: dog
# Line: bird
# Line: cat
Line: cat
Line: dog
Line: bird
Line: cat

Using readlines() to Read All Lines¶

  • The readlines() method reads all lines from a file and returns them as a list of strings, where each string represents a single line from the file (including newline characters).

  • This is useful when:

  • You want to process all lines together.

  • You want to perform filtering or batch operations on file data.

In [ ]:
# Open the file in read mode
with open("info.txt", "r") as file:
    # Read all lines into a list
    lines = file.readlines()

# Display the raw list
print("Raw Lines List:", lines)

# Clean and display each line without newline characters
for line in lines:
    print("Processed Line:", line.strip())

# Expected Output:
# Raw Lines List: ['cat\n', 'dog\n', 'bird\n', 'cat\n']
# Processed Line: cat
# Processed Line: dog
# Processed Line: bird
# Processed Line: cat
Raw Lines List: ['cat\n', 'dog\n', 'bird\n', 'cat\n']
Processed Line: cat
Processed Line: dog
Processed Line: bird
Processed Line: cat

Always Close the File¶

  • When done, always close the file using .close() to ensure system resources are freed and data buffers are flushed.
In [ ]:
# Good practice: close after reading
file = open("info.txt", "r")
print(file.readline())  # Output: cat
file.close()
cat

Recommended: Use with Statement for Auto-Closing¶

In [ ]:
# Auto-closes file even if an error occurs
with open("info.txt", "r") as file:
    for line in file:
        print(line.strip())

# No need to call file.close()
cat
dog
bird
cat

Python File Write¶

Writing to an Existing File¶

  • To write or append content to a file, use the appropriate mode in the open() function:
Mode Description
"a" Append mode – adds new content at the end of the file.
"w" Write mode – replaces the entire content of the file.

Example: Appending to File¶

In [ ]:
# Append a new data to the file
with open("info.txt", "a") as file:
    file.write("dog")

# Read and display the updated file
with open("info.txt", "r") as file:
    print(file.read())

# Output (assumes existing content in file):
# cat
# dog
# bird
# cat
# dog
cat
dog
bird
cat
dog

Example: Overwriting File Content Using "w"¶

  • Using "w" will erase existing content and write new content.
In [ ]:
# Overwrite previous data
with open("info.txt", "w") as file:
    file.write("dog")

# Read and print updated content
with open("info.txt", "r") as file:
    print(file.read())

# Output:
# dog
dog
Use "w" carefully, as it does not preserve any old content.

Creating a New File¶

  • You can also create new files using one of the following modes:
Mode Behavior
"x" Creates a new file. Throws an error if file already exists.
"w" Creates a file if it doesn't exist.
"a" Also creates the file if it doesn't exist.

Example: Creating a New File Using "x"¶

In [ ]:
# Attempt to create a new file (fails if already exists)
try:
    f = open("test.txt", "x")
    print("File created successfully!")
    f.close()
except FileExistsError:
    print("File already exists.")

# Output (if file does not exist):
# File created successfully!
File created successfully!
In [ ]:
# Attempt to create a new file (fails if already exists)
try:
    f = open("info.txt", "x")
    print("File created successfully!")
    f.close()
except FileExistsError:
    print("File already exists.")

# Output (if file does not exist):
# File already exists.
File already exists.

Creating a File Using "w" or "a"¶

In [ ]:
# This will create the file if it does not exist
with open("test_new.txt", "w") as file:
    file.write("dog")

# Output: File created with one line of text
In [ ]:
# This will create the file if it does not exist
with open("test_new.txt", "a") as file:
    file.write("dog")

# Output: File created with one line of text

Python Delete File¶

Deleting a File Using os.remove()¶

  • To delete a file, use the os module’s remove() function.
  • This will permanently remove the file.

Syntax¶

os.remove("filename")
In [ ]:
import os

# Delete a file named 'info.txt'
os.remove("info.txt")
print("File deleted successfully!")

# Output (if file exists):
# File deleted successfully!
File deleted successfully!
  • If the file does not exist, this will raise a FileNotFoundError.
  • To safely delete a file and avoid runtime errors, check if it exists first using os.path.exists().
In [ ]:
import os

file_name = "info.txt"

# Check if the file exists before deleting it
if os.path.exists(file_name):
    os.remove(file_name)
    print(f"{file_name} deleted successfully!")
else:
    print(f"{file_name} does not exist.")

# Output (if file is missing):
# info.txt does not exist.
info.txt does not exist.

Deleting a Folder Using os.rmdir()¶

  • Use os.rmdir() to delete a folder. Note that it only works on empty directories.

Syntax¶

os.rmdir("foldername")
In [ ]:
import os

# Attempt to delete an empty folder
try:
    os.rmdir("data_folder")
    print("Folder deleted successfully!")
except FileNotFoundError:
    print("Folder not found.")
except OSError:
    print("Folder is not empty.")

# Output (if folder is empty and exists):
# Folder deleted successfully!
Folder is not empty.

Renaming Files with os.rename()¶

  • You can rename a file using os.rename(), which takes two arguments:
  • Current file name
  • New file name

Syntax¶

os.rename("old_file.txt", "new_file.txt")
In [ ]:
import os

# Rename file name
os.rename("filename.txt", "filename_new.txt")
print("file renamed successfully!")

# Output:
# file renamed successfully!
file renamed successfully!

Python File Methods¶

No Method Description
1 close() Closes the file and releases the associated resources.
2 detach() Separates the underlying binary buffer from the text wrapper.
3 fileno() Returns the file descriptor (an integer) used by the operating system.
4 flush() Forces the write buffer to be written to the disk.
5 isatty() Checks if the file stream is connected to a terminal (interactive).
6 read() Reads the entire content of the file as a string or bytes.
7 readable() Returns True if the file can be read from, otherwise False.
8 readline() Reads and returns the next line from the file.
9 readlines() Reads the file and returns all lines as a list.
10 seek(offset) Moves the file pointer to a specific byte position.
11 seekable() Checks if the file supports seeking (random access).
12 tell() Returns the current position of the file pointer (in bytes).
13 truncate(size) Resizes the file to the given size in bytes.
14 writable() Returns True if data can be written to the file.
15 write(string) Writes a string or bytes to the file.
16 writelines() Writes a list of strings to the file (no newline added automatically).

1. close()¶

Point Description
Use Case The close() method is used to properly close a file after it has been opened. It ensures that all system resources are released and any buffered output is flushed to disk.
Syntax file.close()
Parameter None — This method does not take any arguments.

Useful Information¶

No. Point Description
1 Closes File Access Once a file is closed, no further read or write operations can be performed without reopening it.
2 Raises Error on Access Accessing a closed file results in a ValueError.
3 Safe to Call Multiple Times You can call close() more than once without causing an error.
4 Important for Buffer Flushing Especially in write mode, closing ensures that all data is actually saved to disk.
5 Good Practice Even though Python auto-closes files when the object is deleted or program ends, explicit closing is considered best practice in production.
In [ ]:
# Open the file in read mode
file = open("info.txt", "r")

# Read the entire content of the file
print(file.read())

# Always close the file to free up resources and flush buffers
file.close()

# Output:
# cat
# dog
# bird
# cat
cat
dog
bird
cat

2. detach()¶

Point Description
Use Case The detach() method is used to separate the underlying binary buffer from a text I/O wrapper (like TextIOWrapper). It is typically used when dealing with streams where you need raw binary access after initial text processing.
Syntax text_io.detach()
Parameter None — This method does not accept any arguments.

Useful Information¶

No. Point Description
1 Applies to Text Wrappers Only available on objects like TextIOWrapper (not standard file objects).
2 Returns Binary Buffer Returns the underlying binary stream (e.g., BufferedReader).
3 Breaks Text Stream After calling detach(), the text wrapper becomes unusable and should not be used.
4 Useful in Encoding Conversion Useful when you want to switch encodings without reopening the stream.
In [ ]:
import io

# Create a binary buffer with some content
binary_stream = io.BytesIO(b"intensity coding - file tutorial")

# Wrap the binary stream with a TextIOWrapper for text-level operations
text_stream = io.TextIOWrapper(binary_stream, encoding='utf-8')

# Detach the text wrapper to access the underlying binary stream
buffer = text_stream.detach()

# Now you can use 'buffer' as a raw binary stream
print(buffer.read())  # Output: b'intensity coding - file tutorial'
b'intensity coding - file tutorial'

3. fileno()¶

Point Description
Use Case The fileno() method returns the underlying file descriptor — a unique integer assigned by the operating system to identify an open file stream. This is especially useful when performing low-level I/O operations.
Syntax file.fileno()
Parameter None — This method does not take any arguments.

Useful Information¶

No. Point Description
1 Returns Integer Descriptor Outputs a numeric file descriptor used internally by the OS for I/O tasks.
2 OS-Dependent May raise an UnsupportedOperation error if the OS or the file stream does not support file descriptors.
3 Low-Level Use Case Typically used when integrating Python file handling with OS-level or external system calls.
4 Works on Open Files Only works on file objects that are currently open.
In [ ]:
# Open a file in read mode
file = open("info.txt", "r")

# Retrieve the file descriptor assigned by the operating system
print(file.fileno())

# Output:
# 49
# (Note: The output number may vary depending on your system and number of open file descriptors)
49

4. flush()¶

Point Description
Use Case The flush() method is used to clear the internal buffer of the file object and force the writing of any buffered data to the disk immediately.
Syntax file.flush()
Parameter None — This method does not take any arguments.

Useful Information¶

No. Point Description
1 Flushes Data Manually Forces buffered content to be written to disk without closing the file.
2 Helpful in Long-Running Programs Useful when writing logs or saving checkpoints in ML training loops.
3 No Need to Reopen You don’t need to close and reopen the file to write unflushed data.
4 Automatically Done on Close Python flushes data automatically when you close the file using close().
5 Doesn't Affect Reading flush() only affects buffered write operations, not read operations.
In [ ]:
# Open file in append mode
file = open("info.txt", "a")

file.write("Dog")

# Force the system to write the content to disk immediately
file.flush()

file.write("bird")

# Closing the file at the end (not shown here) will also flush remaining content
Out[ ]:
4

5. isatty()¶

Point Description
Use Case The isatty() method checks whether the file stream is connected to an interactive terminal device (like a command-line interface).
Syntax file.isatty()
Parameter None — This method does not accept any arguments.

Useful Information¶

No. Point Description
1 Returns a Boolean Returns True if the file stream is attached to a terminal; otherwise, False.
2 Useful in Scripts Helps determine if the script is being run in a terminal or through redirected input/output.
3 Mostly Used with stdin/stdout Typically used with standard input/output streams (sys.stdin, sys.stdout) rather than regular files.
4 Normal Files Return False File objects opened from disk (like .txt files) usually return False.
5 No Output Content The method only returns a boolean value—it does not interact with the file content.
In [ ]:
# Open a text file in read mode
file = open("info.txt", "r")

# Check if the file stream is connected to a terminal (TTY)
print(file.isatty())

# Close the file
file.close()

### Output: (The result is `False` because `info.txt` is a file stored on disk, not an interactive terminal device.)
#False
False

6. read()¶

Point Description
Use Case The read() method retrieves a specified number of bytes (or characters) from a file. If no size is specified, it reads the entire file content.
Syntax file.read(size)
Parameter size (Optional) — The number of bytes/characters to read from the file. If not specified or set to -1, it reads until the end of the file.

Useful Information¶

No. Point Description
1 Reads File Content Fetches file content as a string (text mode) or bytes (binary mode).
2 Default Reads All If size is omitted or set to -1, the method reads the full file content.
3 Reads from Current Cursor Starts reading from the current position of the file pointer.
4 Ideal for Partial Reads Useful when processing large files in chunks or streaming.
5 Moves File Pointer The file cursor advances as characters are read.

Example 1: Read Entire File Content¶

In [ ]:
# Open file in read mode (default is text mode)
file = open("info.txt", "r")

# Read the entire file content
print(file.read())

# Close the file
file.close()

####
# cat
# dog
# bird
# cat
cat
dog
bird
catbird

Example 2: Read Only First 6 Characters¶

In [ ]:
# Open file for reading
file = open("info.txt", "r")

# Read only the first 6 characters from the file
print(file.read(6))

# Close the file
file.close()

# Output:(Also include \n)
# cat
# do
cat
do

7. readable()¶

Point Description
Use Case The readable() method checks if a file stream supports reading operations. It returns True if readable, otherwise False.
Syntax file.readable()
Parameter None — This method does not take any arguments.

Useful Information¶

No. Point Description
1 Checks Read Permission Verifies whether the file object was opened in a mode that allows reading ('r', 'r+', 'w+', etc.).
2 Returns Boolean Returns True if readable; otherwise False.
3 Helpful in Validation Useful in situations where you want to validate the stream before attempting to read—especially in reusable file handling functions.
4 Prevents Runtime Errors Helps avoid io.UnsupportedOperation errors when working with non-readable modes.
In [ ]:
# Open the file in read mode
file = open("info.txt", "r")

# Check whether the file supports read operation
print(file.readable())  # Output: True

# Close the file after checking
file.close()
True

8. readline()¶

Point Description
Use Case The readline() method reads and returns a single line from the file each time it is called. You can optionally limit the number of bytes to read using the size parameter.
Syntax file.readline(size)
Parameter size (Optional) — Specifies the maximum number of bytes to read from the line. Default is -1, which reads the entire line.

Useful Information¶

No. Point Description
1 Reads One Line at a Time Reads a single line from the file where the file pointer is currently positioned.
2 Supports Partial Reading You can limit how many characters (bytes) are read using the size parameter.
3 Used in Iterative Reading Useful when reading large files line-by-line for memory efficiency.
4 File Pointer Advances Each call moves the file pointer to the start of the next line.
5 Stops at Newline (\n) The read operation stops after reaching a newline or when the specified size limit is reached.

Example 1: Read the First Line of a File¶

In [ ]:
# Open the file in read mode
file = open("info.txt", "r")

# Read and print the first line
print(file.readline())  # Output: cat

file.close()
cat

Example 2: Read Two Lines Sequentially¶

In [ ]:
file = open("info.txt", "r")

# Read the first two lines using readline() twice
print(file.readline())  # Output: cat
print(file.readline())  # Output: dog

file.close()
cat

dog

Example 3: Read a Limited Number of Characters from a Line¶

In [ ]:
file = open("info.txt", "r")

# Read only the first 2 characters of the first line
print(file.readline(2))  # Output: ca

file.close()
ca

9. readlines()¶

Point Description
Use Case The readlines() method reads the entire file and returns a list where each element represents a single line from the file. It’s useful when you need all lines at once for further processing.
Syntax file.readlines(hint)
Parameter hint (Optional) — Sets a byte limit for reading lines. Reading stops once the accumulated bytes reach or exceed this hint. If not provided, all lines are read.

Useful Information¶

No. Point Description
1 Returns a List of Lines Each line in the file becomes an element in a list.
2 Newline Characters Included Each line includes the \n at the end unless it's the last line.
3 Memory Usage Suitable for small or medium files; can consume more memory with large files.
4 Hint Controls Read Limit You can control how much data to read using the optional hint parameter.
5 File Pointer Moves The method reads from the current file pointer to the end unless a hint is set.

Example 1: Read All Lines as List Elements¶

In [ ]:
# Open the file in read mode
file = open("info.txt", "r")

# Read all lines into a list
lines = file.readlines()
print(lines)

file.close()

# Output:
# ['cat\n', 'dog\n', 'bird\n', 'cat']
['cat\n', 'dog\n', 'bird\n', 'cat']

Example 2: Limit Lines Using the Hint Parameter¶

In [ ]:
# Open the file in read mode
file = open("info.txt", "r")

# Read lines with a byte-size hint
limited_lines = file.readlines(6)
print(limited_lines)

file.close()

# Output:
#['cat\n', 'dog\n']
['cat\n', 'dog\n']

10. seek()¶

Point Description
Use Case The seek() method is used to move the file pointer to a specific position in a file. This is useful when you want to read from or write to a specific location within the file.
Syntax file.seek(offset, whence)
Parameters offset (Required) — The number of bytes to move the pointer.
whence (Optional) — Controls the reference position for the offset. 0 – Start of the file (default), 1 – Current file position, 2 – End of the file

Useful Information¶

No. Point Description
1 Controls File Pointer Allows repositioning the pointer for both reading and writing.
2 Works in Binary and Text Mode Behavior depends on the mode, especially for text files.
3 a or a+ Mode Restrictions Seeking is ineffective in append-only mode ('a'), but works in 'a+' when reading.
4 Required for Random Access Essential for jumping to specific parts of a file.
5 Returns New Position The method returns the new byte position from the file's beginning.

Example 1: Move Pointer and Read from New Position¶

In [ ]:
# Open the file in read mode
file  = open("info.txt", "r")

# Move the pointer 4 bytes from the start
file.seek(2)

# Read from the new position
print(file.readline())

file.close()

# Output:
# t
t

Example 2: Return Current Position After Seeking¶

In [ ]:
# Open the file in read mode
file = open("info.txt", "r")

# Seek to position 4
pos = file.seek(2)

# Print the new position
print(pos)

file.close()

# Output:
# 2
2

Example 3: Use Whence for Absolute Positioning¶

In [ ]:
# Open the file in read mode
file = open("info.txt", "r")

# Move pointer to 2 bytes from the start (whence = 0)
file.seek(2, 0)

# Read from the new position
print(file.readline())

file.close()

# Output:
# t
t

11. seekable()¶

Point Description
Use Case The seekable() method checks whether the file stream supports random access (i.e., whether the file pointer can be repositioned using methods like seek()).
Syntax file.seekable()
Parameters This method does not take any arguments.

Useful Information¶

No. Point Description
1 Checks File Navigation Capability Indicates if the file allows repositioning of the pointer.
2 Returns Boolean Returns True for seekable files, otherwise False.
3 Depends on File Mode Commonly True for files opened in read ('r') or read+write ('r+') modes.
4 Not Always True Files opened via certain streams (e.g., pipes or sockets) are often not seekable.
5 Helps Avoid Errors Useful before calling seek() to prevent runtime exceptions.
In [ ]:
# Open the file in read mode
file = open("info.txt", "r")

# Check if the file allows pointer movement
print(file.seekable())

file.close()

# Output:
# True
True

12. tell()¶

Point Description
Use Case The tell() method returns the current position of the file pointer, which indicates how many bytes have been read or written from the beginning of the file.
Syntax file.tell()
Parameters This method does not require any parameters.

Useful Information¶

No. Point Description
1 Indicates Pointer Position Shows the byte position where the next read/write will occur.
2 Commonly Used with seek() Often used alongside seek() to control file navigation.
3 Always Returns Byte Offset The value returned is the number of bytes from the file’s start.
4 Works in Both Modes Can be used in both text and binary modes.
5 Helpful for Debugging Useful for tracking data location during file operations.

Example: Check Current File Pointer Position¶

In [ ]:
# Open the file in read mode
file = open("info.txt", "r")

# Display initial pointer position
print(file.tell())  # Output: 0

# Read one line
print(file.readline())  # Output: cat

# Display pointer position after reading
print(file.tell())  # Output: 5 (or number of bytes read)

file.close()
0
cat

5

Example: Using tell() with seek()¶

In [ ]:
# Open the file in read and write mode
file = open("info.txt", "r+")

# Read the first 3 bytes
data = file.read(3)
print("Read String is:", data)
# output: Read String is: cat

# Get current position
position = file.tell()
print("Current file position:", position)
# Output: Current file position: 3

# Move pointer to the beginning
file.seek(0, 0)

# Read again after resetting position
data = file.read(5)
print("Again read String is:", data)
# Output:
# Again read String is: cat
# d

file.close()
Read String is: cat
Current file position: 3
Again read String is: cat
d

13. truncate()¶

Point Description
Use Case The truncate() method is used to resize a file to a specified number of bytes. If no size is provided, it trims the file at the current pointer position.
Syntax file.truncate(size)
Parameter size (Optional) — The desired file size in bytes. If omitted, the file will be truncated at the current file position.

Useful Information¶

No. Point Description
1 Resizes File Shrinks or extends the file to a given byte size.
2 Works in Write Modes Only usable in modes that allow writing ('w', 'a', 'r+', etc.).
3 Size Not Mandatory If size is not passed, truncation occurs at the current file pointer.
4 May Add Padding If the new size is greater than the current size, the result depends on the platform (some may pad with null bytes).
5 Pointer Position Unchanged The current file pointer remains unaffected after truncation.
In [ ]:
# Open the file in append mode
file = open("info.txt", "a")

# Truncate the file to 9 bytes
file.truncate(9)

# Close the file
file.close()

# Reopen and read the truncated content
file = open("info.txt", "r")
print(file.read())
# Output:
# cat
# dog
file.close()
cat
dog

14. writable()¶

Point Description
Use Case The writable() method checks whether the file stream allows writing operations. It returns True if writing is permitted, otherwise False.
Syntax file.writable()
Parameter None — This method does not require any arguments.

Useful Information¶

No. Point Description
1 Indicates Write Permission Tells whether the file supports writing.
2 Depends on Mode Returns True when the file is opened in modes like 'w', 'a', 'w+', or 'a+'.
3 Used in Conditional Logic Useful before performing write operations to avoid runtime errors.
4 Non-Writable Modes Returns False if opened in read-only modes like 'r' or 'rb'.
5 Does Not Modify File This is a check-only method and does not change the file content or pointer.
In [ ]:
# Open the file in append mode
file = open("info.txt", "a")

# Check if the file supports writing
print(file.writable())
# Output: True

# Always good practice to close the file after use
file.close()
True

15. write()¶

Point Description
Use Case The write() method is used to insert a string or byte-like content into a file. It writes the data at the current file stream position.
Syntax file.write(string_or_bytes)
Parameter string_or_bytes — The content (text or byte object) to be written into the file.

Useful Information¶

No. Point Description
1 Affects File Content The method alters the file by writing new content.
2 Depends on File Mode In 'a' mode, data is added at the end; in 'w' mode, the file is cleared before writing.
3 May Require Flushing Content may not appear immediately due to buffering; use flush() or close() to finalize.
4 Returns Number of Characters It returns the number of characters successfully written.
5 Accepts Strings Only Only strings (or bytes if opened in binary mode) are allowed; writing other types raises an error.

Example 1: Writing in Append Mode¶

In [ ]:
# Open the file in append mode - adds text at the end
file = open("info.txt", "a")
file.write("Bird")
file.close()

# Read file content after writing
file = open("info.txt", "r")
print(file.read())

# Output:
# cat
# dog
# bird
# catBird
cat
dog
bird
catBird

Example 2: Writing a New Line¶

In [ ]:
# Open in append mode again, but this time add a new line
file = open("info.txt", "a")
file.write("\nbird")
file.close()

# Read file to verify new line addition
file = open("info.txt", "r")
print(file.read())

# Output:
# cat
# dog
# bird
# cat
# bird
cat
dog
bird
cat
bird

16. writelines()¶

Point Description
Use Case The writelines() method writes multiple strings (usually from a list) into a file in one go, without adding any line breaks automatically.
Syntax file.writelines(list_of_strings)
Parameter list_of_strings — A list of string or byte-like objects to be written into the file. Each item is written in sequence as-is.

Useful Information¶

No. Point Description
1 Inserts Multiple Strings Writes each string from the provided list to the file.
2 No Automatic Newlines Line breaks must be added manually (e.g., using \n) if needed between elements.
3 Respects File Mode In 'a' mode, the content is added at the end; in 'w' mode, the file is cleared before writing.
4 No Return Value This method does not return anything; it modifies the file directly.
5 Accepts Iterable of Strings The method expects an iterable (like a list or tuple) containing string elements.

Example 1: Writing Multiple Strings Without Newlines¶

In [ ]:
# Open the file in append mode and write multiple strings from a list
file = open("info.txt", "a")
file.writelines(["Bird", "dog"])
file.close()

# Read the content of the file after writing
file = open("info.txt", "r")
print(file.read())

# Output:
# cat
# dog
# bird
# catBirddog
cat
dog
bird
catBirddog

Example 2: Writing with Manual Line Breaks¶

In [ ]:
# This time we add newline characters to ensure each string appears on a new line
file = open("info.txt", "a")
file.writelines(["\nBird", "\ndog"])
file.close()

# Read the file to verify the output
file = open("info.txt", "r")
print(file.read())

# Output:
# cat
# dog
# bird
# cat
# Bird
# dog
cat
dog
bird
cat
Bird
dog
Category
Python Natural Language Processing Generative AI
Tag's
Python Natural Language Processing

Quick Links

  • Home
  • Tutorials
  • About Us
  • Contact Us

Tutorials

  • Python
  • Natural Language Processing
  • Generative AI

Tags

  • Python
  • Natural Language Processing

About Intensity Coding

  • Intensity Coding is your learning hub for Data Science, Machine Learning, Deep Learning, NLP, and Generative AI. From beginner to expert level, we offer clear tutorials, real-world examples, and up-to-date insights. Our content simplifies complex topics to help you grow in your AI journey.
Intensity Coding

© 2025 Intensity Coding. All Rights Reserved.

Privacy Policy Terms and Conditions Disclaimer