0

I'm attempting to access a .txt file while accessing a module function I made. Problem is I don't think the function can access the text file. The file has data in it. It goes through the motions of trying to populate it. Do I need a init.py? I'm getting now output in my data.csv file that I'm attempting to output. But my data.txt file has data in it. So I'm not sure what I'm doing wrong. When run the file on it's on not as a module it runs perfectly.

The call:

import csv_generator
#choose to print out in csv or json
    def printData():
        answer = input('Please choose 1 for csv or 2 for jsson output file: ')
        if(answer == '1'):
            csv_generator.csv_write()
        elif(answer == '2'):
            json_writer.json_write()
        else:
            printData()
    
    printData()

The definition:

        import csv
        def csv_write():
        #files to read from 
        data_read = open('data.txt', 'r')
    
        #process data and write to csv file
        with open('data.csv', 'w', newline='') as f:
            thewriter = csv.writer(f)
    
            thewriter.writerow(['Last', 'First', 'Email', 'Address', 'Phone'])
            for x in data_read:
                y = x.split(',')
                thewriter.writerow([y[0].strip(), y[1].strip(), y[2].strip(), y[3].strip(), y[4].strip()])
John Verber
  • 745
  • 2
  • 16
  • 31

2 Answers2

1

Your module opens the files data.txt and data.csv, without specifying a specific path/directory. That means it will try to open the files in the current working directory of the running script.

When you run the module as a script itself, that working directory may be another actual location than the working directory for the script that imports the module.

What the working directory is depends on how you run your script. From the command line, it's typically the working directory of the shell when you start the Python executable. From an IDE, it's typically something you can configure, but by default in most cases it will be the folder the script itself is in.

Either specify the full path of the file (assuming you're on Windows, similar for Linux):

open(r'D:\some\folder\data.csv', 'w', newline='')

Or make it relative to the script, if you need the file to be written in the same folder where the source file is:

from pathlib import Path

open(Path(__file__).parent / 'data.csv', 'w', newline='')
Grismar
  • 27,561
  • 4
  • 31
  • 54
0

I found the problem. It was simple. It has nothing to do with absolute paths. It was simply that I was originally writing to data.txt to use in my code in the example. But I didn't close it before trying to use it again. So when I tried to open it again, just wiped everything I had done (that was stuck in memory I assume) and then was accessing a blank document.

I have it set up now the same way with no absolute path and it works fine. I just had to close that file before using it again.

John Verber
  • 745
  • 2
  • 16
  • 31