Skip to main content

Posts

Showing posts with the label files

seek(), tell() and other functions

  Learning Sections          show seek(), tell() and Other Functions in Python Python provides several functions to manipulate the file pointer while reading or writing files. Here are some commonly used functions: 1. seek() The seek() method sets the file's current position at the offset. The position is calculated from the beginning of the file, unless the optional whence parameter is provided. The whence parameter can take the following values: 0 : default, the beginning of the file 1 : current file position 2 : end of the file # Open the file in read mode with open ( 'example.txt' , 'r' ) as file : # Move the file pointer to the beginning of the file file . seek ( 0 ) # Read the first 10 characters content = file . read ( 10 ) print ( content ) 2. tell() The tell() method returns the current position of the file pointer within the file...

read(), readlines() and other methods in Python

Learning Sections          show read(), readlines() and Other Methods in Python Python provides several methods to read from and manipulate files. Here are some common methods: 1. read() The read() method reads the entire content of a file and returns it as a string. # Open the file in read mode with open ( 'example.txt' , 'r' ) as file : # Read the entire content of the file content = file . read () print ( content ) 2. readlines() The readlines() method reads all the lines of a file and returns a list where each element is a line in the file. # Open the file in read mode with open ( 'example.txt' , 'r' ) as file : # Read all lines of the file lines = file . readlines () for line in lines : print ( line . strip ()) # strip() removes the newline character 3. readline() The readline() method reads one line from the file and returns it as a...

File IO in Python

  Learning Sections          show File IO in Python File Input/Output (IO) operations allow you to read from and write to files. Python provides built-in functions and methods for file handling. 1. Opening a File Use the open() function to open a file. It returns a file object and takes two parameters: the file name and the mode (e.g., read, write, append). # Open a file in read mode file = open ( 'example.txt' , 'r' ) 2. Reading from a File After opening a file, you can read its contents using methods like read() , readline() , or readlines() . # Read entire content of the file content = file . read () print ( content ) # Don't forget to close the file file . close () 3. Writing to a File Open a file in write ( 'w' ) or append ( 'a' ) mode to write data to it. # Open a file in write mode file = open ( 'example.txt' , 'w' ) # Write a string to the...