Python

Constant dripping wears away a stone

File Handling


File Handling: File handling is about how to open a file, read from a file, write into a file, close a file, delete a file, and Python built-in file methods. When a file needs to be accessed, the path to the file needs to be specified if the file is not in the current working directory. The following file is the file that we use for this chapter.

  • Opening a File: open(filename, mode='r'[, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None]): The function returns a file object which is also called a handle. It is a built-in function in Python. The first parameterfilenameis the name of the file to be opened. If the file is not located in the same folder as the program, its path needs to be specified. The second parametermodespecifies in which mode the file is to be opened. The mode tells which action to do to the file: create(x), read(r), write(w), or append(a) to the file. It also tells in which mode the file is to be handled: in text mode or in binary mode. The following is a table of file modes and their corresponding descriptions.
  • Read a File:
    • read([number]): Read and return the content of the file as a raw string. If the parameternumberis given, it returns the firstnumbercharacters as a raw string.
      • number: Optional. An integer. If given, the function returns the firstnumbercharacters.
    • readline(): Read and return a single line of the given file as a raw string.
    • readlines(): Read and return the lines of the file as a list of raw strings.
  • Create a File: To create a new file in Python, use mode'x'in theopen()method. It will report an error if the file already exists.
  • Write to a File:
    • write(str): Write the stringstras a single line to the given file.
    • writelines(aList): Write the strings in the listaListas lines to the given file.
      • aList:A list of strings to be written to the given file.
  • Close a File:
    • close(): Close the given file.
    • open() asfile_object: It is a predefined closing file action. It opens a file and the file will be automatically closed outside the block where it is opened.
  • Delete a File:
    • os.remove(file_name): Delete the file with namefile_name. The OS module needs to be imported first before using this method.
  • Check if a File Exists:
    • os.path.exists(file_name): Check if the file with namefile_nameexists and return True if yes; otherwise, return False. The OS module needs to be imported first before using this method.
    • os.path.isfile(file_name): Check whetherfile_nameis a file and return True if yes; otherwise, return False. The OS module needs to be imported first before using this method.
    • open(file_name): This method can also be used to check whether the file with namefile_nameexists or not. If the file does not exist, report an exception.
  • Rename a File:
    • os.rename(current_file_name, new_file_name) To rename the file with namecurrent_file_nameto a new namenew_file_name.
  • File Position:
    • tell(): Return the current position of the file handle , which is an integer representing the number of bytes from the beginning of the file.
    • seek(offset[, from=0]): Set the position of the file handle to a given specific position.
      • offset: Specifies the number of bytes that the file handle is to move forward.
      • from: Specifies the reference position from where the file handle is to move forwardoffsetbytes. If it is 0, use the beginning of the file as the reference position; if it is 1, use the current position as the reference position; if it is 2, use the end of the file as the reference position.
  • File Object Attributes: The following picture is a list of attributes that are related to file objects.
  • File Directories: A file directory is a folder that contains files. To access to a file, the path to the file's directory needs to be specified if the directory is not the current working directory.
    • Create a Directory:
      • os.mkdir(directory_name): Create a file directory with namedirectory_name.
    • Change the Current Directory:
      • os.chdir(new_directory_name): Change the current directory to the directorynew_directory_name.
    • Display the Current Directory:
      • os.getcwd(): Display the current working directory.
    • List All Files in a Directory:
      • os.listdir(directory_name): List all the files and directories in the directory.
    • Check if a Directory Exists:
      • os.path.isdir(directory_name): Check whether a directory already exists and returns True if it exists; otherwise, returns False.
    • Remove a Directory:
      • os.rmdir(directory_name): Delete a directory. All files in the directory need to be deleted before deleting the directory.