0

I am (trying) to write a tool that will open a file based on user input. I want to eventually write the results of the script into a file and store it into the same directory as the input file.

I currently have this

from Bio import SeqIO
import os, glob


var = raw_input("what is the path to the file (you can drag and drop):")
fname=var.rsplit("/")[-1]
fpath = "/".join(var.rsplit("/")[:-1])

os.chdir(fpath)
#print os.getcwd()

#print fname
#for files in glob.glob("*"):
#    print files

with open(fname, "rU") as f:
    for line in f:
        print line

I do not understand why I cannot open the file. Both the "os.getcwd" and the "glob.glob" part show that I successfully moved to the users directory. In addition, the file is in the correct folder. However, I cannot open the file... any suggestions would be appreciated

3
  • 2
    Why don't you do os.path.join(fname, fpath) instead of the contortions you currently go through with the rsplits and joins? Commented Mar 4, 2013 at 3:31
  • why do you need to change directory. if you know the directory it's stored in just do open(fpath + '/output.txt', 'w') or whatever for the output Commented Mar 4, 2013 at 4:11
  • Need to see an example run of this. It worked fine for me after giving raw_input /home/user/test.txt as input. Though as others have recommended there are probably cleaner ways to go about what you're doing. Commented Mar 4, 2013 at 4:46

2 Answers 2

1

Try this to open the file and get the path to the file:

import os

def file_data_and_path(filename):
    if os.path.isfile(filename):
        path = os.path.dirname(filename)
        with open(filename,"rU") as f:
            lines = f.readlines()
        return lines,path
    else:
        print "Invalid File Path, File Doesn't exist"
        return None,None

msg = 'Absolute Path to file: '
f_name = raw_input(msg).strip()

lines,path = file_data_and_path(f_name)
if lines != None and path != None:
    for line in lines:
        print lines
    print 'Path:',path
Sign up to request clarification or add additional context in comments.

Comments

1

mmm asume you want validations, this maybe can help you :)

def open_files(**kwargs):
    arc = kwargs.get('file')
    if os.path.isfile(arc):
        arc_f = open(arc, 'r')
        lines = arc_f.readlines()
        for line in lines:
            print line.strip()

if __name__ == "__main__":
    p = raw_input("what is the path to the file (you can drag and drop):")
    open_files(file=p)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.