0

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

我目前有这个

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”部分都表明我已成功移至用户目录。此外,该文件位于正确的文件夹中。但是,我无法打开文件...任何建议将不胜感激

4

2 回答 2

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
于 2013-03-04T07:04:18.110 回答
1

嗯,假设您需要验证,这可能会对您有所帮助:)

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)
于 2013-03-04T05:04:56.740 回答