Python Import from File – Importing Local Files in Python

There are many reasons you might want to import files in Python. Perhaps you're doing data analysis, custom file processing, file manipulation, automation and so on.

Fortunately, Python provides a number of ways and methods to help you accomplish this task.

In this article, we will examine some of these methods and approaches. We will walk through an example for each method and discuss best practices.

How to Import Files in Python Using Built-in Python Functions

For reading text files, we can use the open() function to open the file in read mode and then read its contents using methods like read()readline(), or readlines().

Then to write data to a text file, we can open the file in write mode using open(), and then use the write() method to write data into the file.

How to open a file:

To open a file, we can use the open() function. It takes two arguments: the file path and the mode in which we want to open the file (read mode, write mode, append mode, and so on).

For example, to open a file named "data.txt" in read mode located in the current directory, we can use the following code:

file = open("data.txt", "r")

How to read file content:

After opening the file, we can read its content using various methods. The most commonly used methods are:

  • read(): Reads the entire content of the file as a single string.
  • readline(): Reads a single line from the file.
  • readlines(): Reads all lines from the file and returns them as a list of strings.

Here's an example that reads and prints the content of a file line by line:

file = open("data.txt", "r")
for line in file.readlines():

How to write to a file:

To write data to a file, open it in write mode ("w") or append mode ("a"). In write mode, the existing content of the file is overwritten. In append mode, new content is added to the end of the file. After opening the file, we can use the write() method to write data to the file.

Here's an example that writes a list of names to a file named "names.txt":

names = ["John", "Alice", "Bob"]

file = open("names.txt", "w")
for name in names:
    file.write(name + "\n")

Note: It's important to close the file using the close() method after you finish reading or writing to it. This ensures that any changes made to the file are saved and resources are freed.

How to Import Files in Python Using the Pandas Library

For importing CSV files, we can use the read_csv() function from the Pandas library. This function automatically loads the data into a DataFrame, providing powerful data manipulation capabilities.

To work with Excel files, Pandas provides the read_excel() function, which reads the data from an Excel file and returns a DataFrame.

Back to Top