如何在python中通过用户输入打开文件

时间:2013-03-04 03:23:46

标签: python

我(尝试)编写一个可以根据用户输入打开文件的工具。 我想最终将脚本的结果写入文件并将其存储到与输入文件相同的目录中。

我目前有这个

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

我不明白为什么我无法打开文件。 “os.getcwd”和“glob.glob”部分都显示我已成功移动到users目录。此外,该文件位于正确的文件夹中。但是,我无法打开文件... 任何建议将不胜感激

2 个答案:

答案 0 :(得分:1)

mmm如果你想要验证,这可能可以帮助你:)

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)

答案 1 :(得分:1)

尝试此操作打开文件并获取文件的路径:

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