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

0 投票
2 回答
11507 浏览
提问于 2025-04-17 17:49

我正在尝试写一个工具,根据用户输入打开一个文件。最终,我想把脚本的结果写入一个文件,并把它存储在和输入文件相同的文件夹里。

我现在有这个代码:

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”这两个部分显示我已经成功进入了用户的目录。而且,文件也在正确的文件夹里。但是,我就是打不开这个文件……如果有任何建议,我会很感激。

2 个回答

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)
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

撰写回答