0

I wanted to supply python with a windows 'data path' that could be used to set up input processing. I googled this with no luck, and now figure I am on my own.

There appears to be many ways of reading in a file with python, and after some frustration with "\" and "/" and windows path names I found a way to get my data path set up. It is not a general approach but should serve me well.

Related Questions: Is this code ugly? Is this a nonstandard method? Are there elegant features in 3.6 that should be used?

### Title: Process an input file using a 'data path' for a user on windows
import sys 
import os
print("OK, starting program...")

file_processed = False
for path, dirs, files in os.walk("/Users/Mike"):
    if file_processed: break
    for file in files:
        if file_processed: break
        if file == 'seriousdata.txt':
            my_path = os.path.abspath(path)
            my_dsn = os.path.join(my_path, file)
            print("Opening txt file " + my_dsn + " for input.")
            with open(my_dsn) as da_lines:
                textlines = (line.rstrip('\r\n') for line in da_lines)
                for line in textlines:
                    print(line)
            file_processed = True
if file_processed:
    pass
else:
    print("File not found")

print("OK, program execution has ended.")
sys.exit() # END SAMPLE CODE SNIPPET
CopyPasteIt
  • 532
  • 1
  • 8
  • 22
  • Do you need to walk the entire directory tree to find seriousdata.txt? If you already know where the file is, it would be much simpler to specify the path as a command line argument. If you're having trouble with that, maybe see [this answer](https://stackoverflow.com/a/9881125/9200529). – Nathan Vērzemnieks Jan 14 '18 at 03:24

2 Answers2

1

From looking at your code, I'm assuming that you want to start at one directory, and move through each child directory, printing out the matching filename's contents if it is found.

If so, then this is way to do this with recursion:

import os

def recursive_list(path, filename):
    files = os.listdir(path)
    for name in files:
        try:
            p = os.path.join(path, name)
            if os.path.isdir(p):
                recursive_list(p, filename)
            else:
                if name == filename:
                    with open(p, "r") as f:
                        print(f.read())
        except PermissionError:
            pass
    return

recursive_list("/home/jebby/Desktop","some_file.txt")

This will start out listing files in path. For every file that is found, if that file is a directory, then the function itself is called (Starting at the path to that folder). If filename matches the name of any file in the current directory, it will be printed (if the user has permissions for that file).

Otherwise, if you only want to read the filename from a known directory without walking down the directory tree:

import os

data_path = "/home/jebby/Desktop"
file_you_want = "filename.txt"
with open(os.path.join(data_path, file_you_want), "r") as f:
    content = f.read()
print(content)
Jebby
  • 1,845
  • 1
  • 12
  • 25
  • I liked your recursion code - can easily adapt it to search for duplicates starting in a root directory. (+1) – CopyPasteIt Jan 14 '18 at 13:37
  • I was aware of the 2nd solution but just thought that I was missing something with python path, windows path, windows env variables, relative path, etc, – CopyPasteIt Jan 14 '18 at 13:41
0

The main question would be : Do you know the location of the file? Jebby has an answer to crawl through the directories.

Here is a solution without using "import os"

dir_fullpath = "c:/project_folder/data"
dir_path = "data"
filename = "file.txt"
try:
   f = open(dir_path + "/" + filename, 'r')
#  print("open " +dir_path + "\" + filename)
#  data=[]
   for line in f:
     print (line.rstrip())
#    data.append(line.rstrip()) 
   f.close()

except IOError:
   print("Fail to open" + dir_path + "\" + filename)
  • It looks like your dir_fullpath is related to pythonpath or current-working-directory and you are using the 'relative path concept'. Are you saying that dir_fullpath = 'C:\Users\Mike\AppData\Local\Programs\Python\Data'? – CopyPasteIt Jan 14 '18 at 13:05