0

I have a list of countries with corresponding .csv files. When I attempt to read_csv iterated over the list with a for loop, I get an error.

I tried generating an empty dict first and making a dict of dataframes, I tried using decode, I tried using item = r'{}.csv'.format(file) instead of just item = '{}.csv'.format(file).

import pandas as pd
import string as str
fileslist = []
with open('data/files.txt') as f:
    for line in f:
        fileslist.append(f.readline().strip())
for file in fileslist:
    item = '{}.csv'.format(file)
    print(item)
    item = pd.read_csv(item)

This should give me a number of dataframes starting with a dataframe named algeria. Instead I get the error "FileNotFoundError: File b'algeria.csv' does not exist".

DanielK
  • 3
  • 1
  • Are you sure you're not just being a goof? Shouldn't it be `data/algeria.csv`? The fact that the string is a binary representation shouldn't actually matter. – Nick Chapman Dec 26 '18 at 20:45
  • Oh and to clarify, the `b` prefix in front of the string just means that it's a binary string, which you can read more about here: https://stackoverflow.com/questions/17615414/how-to-convert-binary-string-to-normal-string-in-python3 and here: https://docs.python.org/3/library/stdtypes.html#str – Nick Chapman Dec 26 '18 at 20:48

1 Answers1

0

This code may help you

import os
import pandas as pd

fileslist = []

with open("data/files.txt", mode='r', encoding="utf-8") as fp:
    for line in fp.readlines():
        fileslist.append(line.strip())

for file in fileslist:
    # make sure your files are in same directory
    # if they are in data folder then don't forget to add 'data/{}.csv'.format(file)

    item = '{}.csv'.format(file)

    if os.path.isfile(item):
        item = pd.read_csv(item)
ozcanyarimdunya
  • 2,324
  • 1
  • 18
  • 21
  • This is the correct answer to my question. However, for anyone reading this for future reference, this generates uncallable variables so you still need to make a dictionary of dataframes. – DanielK Dec 26 '18 at 22:28