0

I have packaged a python file with with setuptools, unfortunately I encounter FileNotFound when I import the project in other directory. What is the correct way of importing a text file inside a script?

project structure:

main_folder/
├─ MANIFEST.in
├─ setup.py
├─ mypgk/
│  ├─ __init__.py
│  ├─ main.py
│  ├─ files/
│  │  ├─ somewhat.csv

here is my setup.py

from setuptools import setup, find_packages

setup(
    name='mypkg',
    version='0.0.1',
    packages=find_packages(exclude=('test*', 'testing*'))
)

MANIFEST.in

recursive-include mypkg *.csv

main.py:

import csv 

config_file = os.path.join('mypkg', 'files', 'somewhat.csv') 
with open(config_file, 'r') as config_file:
    reader = csv.reader(config_file)

running this script in the same directory works, but when I use it on other directories, FileNotFound error is prompted, Have I missed something?

oddly when I type python setup.py sdist it is confirmed in the distribution

copying MANIFEST.in -> mypkg-0.0.1
copying setup.py -> mypkg-0.0.1
copying mypkg\main.py -> mypkg-0.0.1\mypkg
copying mypkg\__init__.py -> mypkg-0.0.1\mypkg
copying mypkg.egg-info\PKG-INFO -> mypkg-0.0.1\mypkg.egg-info
copying mypkg.egg-info\SOURCES.txt -> mypkg-0.0.1\mypkg.egg-info
copying mypkg.egg-info\dependency_links.txt -> mypkg-0.0.1\mypkg.egg-info
copying mypkg.egg-info\top_level.txt -> mypkg-0.0.1\mypkg.egg-info
copying mypkg\files\somewhat.csv -> mypkg-0.0.1\mypkg\files

but going in the directory, I found no files folder

Led
  • 662
  • 1
  • 19
  • 41

1 Answers1

0

To put @Tim Roberts answer in to your example:

import csv 

config_file = os.path.join(os.path.dirname(__file__), 'files', 'somewhat.csv') 
with open(config_file, 'r') as config_file: 
    reader = csv.reader(config_file)

This should work as long as the files directory stays in the same directory as main.py. The name of the directory that contains them would no longer matter

Matt Dassow
  • 1
  • 1
  • 3
  • checked the generated packages file and the file folder seems to be missing, but it is present when I run `python setup.py sdist` – Led Jun 11 '21 at 03:30
  • 1
    `MANIFEST.in` works only for `sdist`. See https://stackoverflow.com/search?q=%5Bsetuptools%5D+include+package+data – phd Jun 11 '21 at 14:58