Skip to content
  • YouTube
  • FaceBook
  • Twitter
  • Instagram

Data Analytics Ireland

Data Analytics and Video Tutorials

  • Home
  • Contact
  • About Us
    • Latest
    • Write for us
    • Learn more information about our website
  • Useful Links
  • Glossary
  • All Categories
  • Faq
  • Livestream
  • Toggle search form
  • How to Create an XML file from Excel using Python Python
  • What Is An Array In Python? array
  • How can I filter my data in Tableau? data visualisation
  • Python Tutorial: How to sort lists Python Lists
  • how to add sine and cosine in python code numpy
  • What is GITHUB, and should I use it? github
  • How to connect to your data in Tableau data visualisation
  • data cleansing in a business environment Articles

TypeError: expected str, bytes or os.PathLike object, not DataFrame

Posted on February 18, 2023March 12, 2023 By admin

Estimated reading time: 3 minutes

If you are working with files and trying to open them to read in their contents, sometimes errors will pop in that may not immediately be obvious how to resolve.

In this blog post, we discuss a TypeError that is associated with opening a file in Python and reading in its contents.

So how may this issue appear?

To start off you have a file that has some contents in it, and you would like to read it. We have created a file called countries.txt, which we are going to try and read in and print. The contents of the file are as follows:

     Name   Capital
0  Ireland   Dublin
1   Englad   London
2    Wales  Cardiff
3   France    Paris

Separate from this you are going to create a data frame that will have data that will match what is in the text file, this is for comparative purposes only. The logic for this is as follows:

import pandas as pd

country_data = {'Name': ['Ireland', 'Englad', 'Wales', 'France'],
        'Capital': ['Dublin','London','Cardiff', 'Paris'],}

# Convert the dictionary into DataFrame
df = pd.DataFrame(country_data)
print(df)

As a follow on, you are going to use a with open statement like the one below, which will read the contents of the file and then print them.

with open(name of file, 'r', encoding='utf-8') as fileopen:
    data_in_file = fileopen.readlines()
    print(data_in_file)

So when you run both of them you get the following error:

Traceback (most recent call last):
  File "C:/Users/haugh/OneDrive/dataanalyticsireland/YOUTUBE/test/youtube.py", line 10, in <module>
    with open(df, 'r', encoding='utf-8') as fileopen:
TypeError: expected str, bytes or os.PathLike object, not DataFrame
      Name  Capital
0  Ireland   Dublin
1   Englad   London
2    Wales  Cardiff
3   France    Paris

So what causes this problem?

The problem lies in where you have referenced ‘df’. In the with open statement, we have passed the wrong data type, that being ‘df’ which is a data frame. The logic expects a string to be passed, and the string in this instance should be ‘countries.txt’

When we correct the logic, the error disappears, and the resulting output will be as follows:

mport pandas as pd

country_data = {'Name': ['Ireland', 'Englad', 'Wales', 'France'],
        'Capital': ['Dublin','London','Cardiff', 'Paris'],}

# Convert the dictionary into DataFrame
df = pd.DataFrame(country_data)
print(df)

with open('countries.txt', 'r', encoding='utf-8') as fileopen:
    data_in_file = fileopen.readlines()
    print(data_in_file)

Output:
      Name  Capital
0  Ireland   Dublin
1   Englad   London
2    Wales  Cardiff
3   France    Paris
['     Name   Capital\n', '0  Ireland   Dublin\n', '1   Englad   London\n', '2    Wales  Cardiff\n', '3   France    Paris']

Process finished with exit code 0

What happens if I pass ‘df’ as a string?

If we simply pass ‘df’ as a string, as follows:

import pandas as pd

country_data = {'Name': ['Ireland', 'Englad', 'Wales', 'France'],
        'Capital': ['Dublin','London','Cardiff', 'Paris'],}

# Convert the dictionary into DataFrame
df = pd.DataFrame(country_data)
print(df)

with open('df', 'r', encoding='utf-8') as fileopen:
    data_in_file = fileopen.readlines()
    print(data_in_file)

We get the following output:

      Name  Capital
0  Ireland   Dublin
1   Englad   London
2    Wales  Cardiff
3   France    Paris
Traceback (most recent call last):
  File "C:/Users/haugh/OneDrive/dataanalyticsireland/YOUTUBE/test/youtube.py", line 10, in <module>
    with open('df', 'r', encoding='utf-8') as fileopen:
FileNotFoundError: [Errno 2] No such file or directory: 'df'

In essence, the logic is looking to open a file, not a data frame. So you should always be referring to a file with its extension inside the string for the program to complete with no errors.

Python, Python Dataframe, strings, type error Tags:Data Frame, File Open, Open a file, Python

Post navigation

Previous Post: TypeError: not all arguments converted during string formatting
Next Post: What are Lambda functions in Python?

Related Posts

  • String Manipulation in Python python method
  • How To Run Python Validation From Javascript Javascript
  • TypeError: the first argument must be callable Python
  • how to add sine and cosine in python code numpy
  • How to create a combobox in tkinter Python
  • How Would You Change The Name Of a Key in a Python Dictionary Python

Select your language!

  • हिंदी
  • Español
  • Português
  • Français
  • Italiano
  • Deutsch
  • How to create a calculated field in Tableau data visualisation
  • TypeError: Array() Argument 1 Must Be A Unicode Character, Not List array
  • How can packages be managed in Julia? Julia programming
  • TypeError object of type ‘int’ has no len() Python
  • How to Generate Random Integers Between 0 and 9 Python
  • how to copy/paste special a range of cells with xlwings Python
  • How To Create An Empty Dictionary In Python python dictionaries
  • IndexError: single positional indexer is out-of-bounds Index Error

Copyright © 2023 Data Analytics Ireland.

Powered by PressBook Premium theme

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT