Change language

File objects in Python

| | |

The file object allows us to use, access and manipulate all files available to the user. Any such files can be read and written.
When a file operation fails due to I / O, an IOError exception is thrown. This includes situations where the operation is undefined for some reason, such as seek () on a tty device or writing a file open for reading.
Files have the following methods:

  • open (): opens the file in the specified access mode.
     open (file_address, access_mode) 

    File access examples: a file can be opened using the built-in open () function. This function takes a file address and access_mode and returns a file object.
    There are different types of access_modes:

      r:  Opens a file for reading only  r +:  Opens a file for both reading and writing  w:  Opens a file for writing only  w +:  Open a file for writing and reading.  a:  Opens a file for appending  a +:  Opens a file for both appending and reading 

    When you add "b" to access mode, you can read the file in binary rather than the default text format. It is used when accessing the file is not in text.

  • read ([size]) : It reads the entire file and returns its contents as a string. Reads no more than size bytes from a file (less if read reaches EOF before size bytes are received). If size argument is negative or omitted, read all data until EOF is reached.

    # Read file

    f = open (__ file__, ’r’ )

      
    # read ()

    text = f.read ( 10 )

     

    print (text)

    f.close ()

  • readline ([size]) : it reads the first line of the file, i.e. up to a newline character or EOF in the case of a single-line file and returns a string. If size is present and non-negative, this is the maximum byte count (including trailing newlines) and an incomplete string may be returned. An empty string is returned only when EOF is encountered immediately.

    # Read line in file

    f = open (__ file__, ’ r’ )

     
    # readline ()

    text = f.readline ( 20 )

    print (text)

    f.close ()

  • readlines ([sizehint]) : It reads a line of the file line by line and updates each line to the returned list. Read up to EOF using readline (), and don’t return a list containing lines read this way. If the optional argument sizehint is present, instead of reading to EOF, reads whole lines of approximately sizehint bytes (possibly after rounding to the internal buffer size).

    # Read file

    f = open (__ file__, ’r’ )

     
    # readline ()

    text = f.readlines ( 25 )

    print (text)

    f.close ()

  • write (stri ng) : Writes the contents of the line to a file. It has no return value. Due to buffering, the line may not appear in the file until the flush () or close () method is called.

    # Writing the file

    f = open (__ file__, ’ w’ )

    line = ’ Welcome Geeks ’

      
    # write ()
    f.write (line)
    f.close ()

    More examples in different modes:

    # H file streaming and writing

    f = open (__ file__, ’r +’ )

    lines = f.read ()

    f.write (lines)
    f.close ()

    # Writing and reading file

    f = open (__ file__, ’w +’ )

    lines = f.read ()

    f.write (lines)
    f.close ()

    # Add file

    f = open (__ file__, ’a’ )

    lines = ’Welcome Geeks ’

    f.write (lines)
    f.close ()

    # Add and read file

    f = open (__ file__, ’ a + ’ )

    lines = f.read ()

    f.write (lines)
    f.close ()

  • writelines (sequence) : This is a sequence of lines in a file, usually a list of lines or any other type of iterative data. It has no return value.

    # Writing the file

    f = open (__ file__, ’a +’ )

    lines = f.readlines ()

     
    # writelines ()
    f.writelines (lines)
    f.close ()

  • tell () : Returns an integer that tells us the position of the file object from the beginning of the file as bytes.

    # С summarize the file object position

    f = open (__ file__, ’r’ )

    lines = f.read ( 10 )

     
    # say ()

    print (f.tell ())

    f.close ()

  • seek (offset, from_where) : Used to change the position of the file object. The offset indicates the number of bytes that will be moved. from_where specifies where the bytes should be moved from.

    # Setting the position of the file object

    f = open (__ file__, ’r’ )

    lines = f.read ( 10 )

    print (lines)

      
    # strive ()

    print ( f.seek ( 2 , 2 ))

    lines = f.read ( 10 )

    print (lines)

    f.close ()

  • flush () : flush the internal buffer, as in stdio fflush (). It has no return value. close () flushes data automatically, but if you want to flush data before closing the file, you can use this method.

    # Clearing the internal buffer before closing the file

    f = open (__ file__, ’ r’ )

    lines = f.read ( 10 )

     
    # blush ()
    f.flush ()

    print (f.read ())

    f.close ()

  • fileno () : Returns an integer file descriptor that is used by the underlying implementation to request I / O from the operating system.

    # Get an integer file descriptor

    f = open (__ file__, ’r’ )

     
    # fileno ()

    print (f.fileno ())

    f.close ()

  • isatty () : Returns True if the file is connected to a tty (-like ) device, and False if not.

    # Checks if the file is connected to a tty (-like) device

    f = open (__ file__, ’r’ )

      
    # isatty ()

    print (f.isatty ())

    f.close ()

  • next () : Used when a file is used as an iterator. The method is called repeatedly. This method returns the next line of input or raises StopIteration in EOF when the file is open for reading (no behavior defined when opening for writing).

    # Loops through the file

    f = open (__ file__, ’ r’ )

     
    # next ()

    try :

    while f. next ():

      print (f. next ())

    except :

    f.close ()

  • truncate ([size]) : truncate file size. If the optional size argument is specified, the file is truncated to (maximum) that size. The default size corresponds to the current position. The current file position does not change. Note that if the specified size exceeds the current file size, the result is platform-dependent: the options are: the file can remain unchanged, grow to the specified size as if it were filled with zeros, or grow to the specified size with undefined new content.

    # Truncates the file

    f = open (__ file__, ’w’ )

     
    # truncate ()

    f.truncate ( 10 )

    f.close ()

  • close () : used to closing an open file. The closed file can no longer be read or written.

  • Attributes :
    • closed : Returns a boolean value indicating the current state of the file object ... It returns true if the file is closed and false when the file is open.
    • encoding : The encoding this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding.
    • mode : I / O mode for the file. If the file was created using the built-in open () function, this will be the value of the mode parameter.
    • name : If the file object was created using open (), the file name.
    • newlines : A file object that was opened in generic newline mode has this attribute, which reflects the newline convention used in the file. The values ​​for this attribute are “/ r”, “/ n”, “/ r / n”, None, or a tuple containing all visible newline types.
    • softspace : This is a boolean a value that specifies whether to print a space character before another value when using a print statement.

  • # Opening and closing a file

    f = open (__ file__, ’ r’ )

     
    # close ()
    f.close ()

    f = open (__ file__, ’a +’ )

    print (f.closed)

    print (f.encoding)

    print (f.mode)

    print (f.newlines)

    print (f.softspace)

Related article:

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically