Python получить атрибуты файла

File Objects in Python

In this tutorial, you’ll learn file objects. Also, we will see how to use file object methods and attributes to perform various file operations.

Table of contents

  • What is the File Object?
  • Types of File Object
    • Text files (TextIOWrapper)
    • Binary Files (BufferedReader and BufferedWriter)
    • Raw Files
    • read() Method
    • readline() Method
    • readlines() Method
    • readable() Method
    • truncate(size) Method
    • write() Method
    • writelines() Method
    • writable() Method
    • close() Method
    • seek() and tell() method
    • fileno() Method
    • flush() Method
    • isatty() Method

    What is the File Object?

    Python file object provides methods and attributes to access and manipulate files. Using file objects, we can read or write any files.

    Whenever we open a file to perform any operations on it, Python returns a file object. To create a file object in Python use the built-in functions, such as open() and os.popen() .

    IOError exception is raised when a file object is misused, or file operation fails for an I/O-related reason. For example, when you try to write to a file when a file is opened in read-only mode.

    Types of File Object

    In Python, there are three different categories of a file object, which are listed below:

    All file types objects are defined in the io module.

    Text files ( TextIOWrapper )

    The text file type is most common. Usually, we use text files to store character data or storing information in plain text with no special formatting beyond basic fonts and font styles.

    We open a text file using the open() function. For example, open(‘test’.txt’, ‘r’) . When we open a text file, it returns a TextIOWrapper file object.

    file = open('test.txt', 'w') print(type(file)) # Output:

    Binary Files ( BufferedReader and BufferedWriter )

    Data is stored on a disk in the form of binary. For example, we use binary files to store data like images or videos. Binary files are a computer-readable form of storing data.

    A program is needed to interpret the data in a binary file and display it to the user. The binary files are also called buffered files. This file type is used for reading and writing binary data.

    Open the binary files using the open() function in binary mode. For example, open(‘abc.txt’, ‘rb’) . It opens the file to read-only in binary mode. The file pointer exists at the beginning of the file.

    The open() function will return the BufferedReader when we open the binary file for reading and the BufferedWriter file object when we open a binary file for writing.

    file = open('test.txt', 'rb') print(type(file)) # Output:

    Raw Files

    A raw file is a collection of unprocessed data. It means the raw file has not been altered or manipulated in any way by the computer.

    The raw files are also called unbuffered files, and this file type is generally used as a low-level building block for binary and text streams. Mostly, The raw file is not used.

    When we open these files, using the open() function will return a FileIO object.

    file = open('test.txt', 'rb', buffering=0) print(type(file)) # Output:

    File Object Attributes

    File object has the following attributes that we can use to accessing various details of a file, such as a file name and under which mode the file is opened.

    • name : Return the name of the file. It is a read-only attribute and may not be present on all file-like objects. If the file object was created using the open() function, the file’s name is returned. Otherwise, some string indicates the source of the file object is returned.
    • encoding : It returns the encoding this file uses, such as UTF-8. This attribute is read-only. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. It may also be None. In that case, the file uses the system default encoding for converting Unicode strings.
    • mode : Returns the file access mode used while opening a file.
    • closed : Returns True if a file is closed. It is a boolean value indicating the current state of the file object.
    • newline : Files opened in universal newline read mode keep track of the newlines encountered while reading the file. The values are ‘\r’, ‘\n’, ‘\r\n’, None (no newlines read yet), or a tuple containing all the newline types seen. For files not opened in universal newline read mode, the value of this attribute will be None
    with open(r'E:\pynative\files\test.txt', "r") as fp: print('Is Closed:', fp.closed) print('Encoding Used:', fp.encoding) print('Access Mode:', fp.mode) print('NewLines Found:', fp.newlines)

    File Object Methods

    File object has the following methods that we can use to accessing a file: A file can be opened with a built-in function called open() . This function takes in the file’s path and the access mode and returns a file object.

    Let’s see each method one by one.

    read() Method

    • The size represents the number of bytes to read from a file. It returns file content in a string object.
    • If size is not specified, it reads all content from a file
    • If the size argument is negative or not specified, read all data until EOF is reached.
    • An empty string is returned when EOF is encountered immediately.
    • When used in non-blocking mode, less data than requested may be returned, even if no size parameter was given.
    # read(size) with open(r'E:\pynative\files\test.txt', 'r') as fp: # read 14 bytes # fp is file object print(fp.read(14)) # read all remaining content print(fp.read())
    My First Line My Second Line My Third Line

    readline() Method

    • Read one line from a file at a time. It returns the line in a string format.
    • If the size is given it reads the number of bytes (including the trailing newline) from a file.
    • If the size argument is negative or not specified, it read a single line
    • An empty string is returned when EOF is encountered immediately.
    # readline(size) with open(r'E:\pynative\files\test.txt', 'r') as fp: # read single line print(fp.readline()) # read next line print(fp.readline()) 
    My First Line My Second Line

    readlines() Method

    • Read all lines from a file and return them in the form of a list object.
    • If the sizehint argument is present, instead of reading the entire file, whole lines totaling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read
    # read(size) with open(r'E:\pynative\files\test.txt', 'r') as fp: # read all lines print(fp.readlines()) 
    ['My First Line\n', 'My Second Line\n', 'My Third Line']

    readable() Method

    It checks whether the file stream can be read or not.

    # read(size) with open(r'E:\pynative\files\test.txt', 'r') as fp: # check if file object is readable print(fp.readable()) # Output True

    truncate(size) Method

    Use the truncate() method to make the file empty.

    • If the optional size argument is present, the file is truncated to (at most) that size. So, for example, if you specify 10 bytes, truncate() will remove the first ten bytes from a file.
    • The size defaults to the current position of a file pointer
    • The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content. Availability: Windows, many Unix variants.
    with open(r'E:\pynative\files\test.txt', 'a') as fp: fp.truncate(5) 

    write() Method

    Write a string to the file. If buffering is used, the line may not show up in the file until the flush() or close() method is called.

    with open(r'E:\pynative\files\test.txt', 'w') as fp: fp.write('My New Line') 

    Read More: Complete guide on write to file in Python

    writelines() Method

    • Write a list of strings to the file. Use to write multiple lines at a time to a file. You can write any iterable object producing strings, typically a list of strings.
    • Note: writelines() do not add line separators.
    with open(r'E:\pynative\files\test.txt', 'w') as fp: data = ['line1\n', 'line2\n', 'line3\n'] fp.writelines(data) 

    writable() Method

    It checks whether the file can be written to or not.

    # read(size) with open(r'E:\pynative\files\test.txt', 'w') as fp: # check if file object is readable print(fp.writeable()) # Output True

    close() Method

    Close the opened file. A closed file cannot be read or written anymore. The ValueError will be raised if you try to read or write a closed file.

    fp = open(r'E:\pynative\files\test.txt', 'r') print(fp.read()) # close file fp.close()

    Note: It is good practice to open a file using the with statement. It automatically closes the file and ensures that all the resources tied up with the file are released.

    seek() and tell() method

    The seek() function sets the position of a file pointer and the tell() function returns the current position of a file pointer.

    with open(r'E:\pynative\files\test.txt', "r") as fp: # Moving the file handle to 6th character fp.seek(6) # read file print(fp.read()) # get current position of file pointer print(fp.tell()) 

    fileno() Method

    Return the integer file descriptor used by the underlying implementation system to request I/O operations from the operating system. This can be useful for other lower-level interfaces that use file descriptors, such as os.read() .

    with open(r'E:\pynative\files\test.txt', "r") as fp: print(fp.fileno()) # Output 3

    flush() Method

    As the name suggests, it flushes the internal buffer. When buffering is used, and if you are writing to a file. the line may not show up in the file until the flush() or close() method is called.

    with open(r'E:\pynative\files\test.txt', "w") as fp: fp.write('New Line') fp.flush() 

    isatty() Method

    Return True if the file is connected to a TTY device like a teleprinter, else False. It let you know that whether the file stream is interactive or not.

    with open(r'E:\pynative\files\test.txt', "r") as fp: print(fp.isatty()) # Output False

    Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

    About Vishal

    I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

    Python Exercises and Quizzes

    Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

    • 15+ Topic-specific Exercises and Quizzes
    • Each Exercise contains 10 questions
    • Each Quiz contains 12-15 MCQ

    Источник

    Читайте также:  Http forum soate ru viewforum php
Оцените статью