简体   繁体   English

如何获取在python中选择为输入文件的文件的绝对路径?

[英]How to get absolute path of the file selected as input file in python?

I want the absolute path of the file selected as input file (from file browser in the form) using the python code below:我想要使​​用下面的python代码选择作为输入文件的文件的绝对路径(来自表单中的文件浏览器):

 for attr, document in request.files.iteritems():
        orig_filename = document.filename
        print os.path.abspath(orig_filename)
        mhash = get_hash_for_doc(orig_filename)

This prints the path of current working directory along(where the python script is executing) with the 'orig_filename' appended to it, which is the wrong path.这会打印当前工作目录的路径(python 脚本正在执行的位置),并附加了“orig_filename”,这是错误的路径。 I am using python 2.7, flask 0.12 under linux OS.我在 linux 操作系统下使用 python 2.7,flask 0.12。

The requirement is to find the hash value of the file before uploading it to the server to check deduplication.要求是在将文件上传到服务器以检查重复数据删除之前找到文件的哈希值。 So I need to use the algorithm by passing the file selected for hashing to another function as:所以我需要通过将选择用于散列的文件传递给另一个函数来使用该算法:

def get_hash_for_doc(orig_filename):
    mhash = None
    hash = sha1()#md5()
    with open(mfile, "rb") as f:
        for chunk in iter(lambda: f.read(128 * hash.block_size), b""):
            hash.update(chunk)
    mhash = hash.hexdigest()

    return mhash

In this function I want to read file from absolute path of the orig_filename before uploading.在这个函数中,我想在上传之前从 orig_filename 的绝对路径读取文件。 Avoided all other code checks here.在这里避免了所有其他代码检查。

First you need to create a temp file to simulate this required file then make your process on it首先,您需要创建一个临时文件来模拟此所需文件,然后在其上进行处理

import tempfile, os
try:
    fd, tmp = tempfile.mkstemp()
    with os.fdopen(fd, 'w') as out:
        out.write(file.read())
    mhash = get_hash_for_doc(tmp)
finally:
    os.unlink(tmp)

If you want to find a folder/file.ext, for an input file, simply use 'os.path.abspath' like:如果要查找文件夹/file.ext,对于输入文件,只需使用“os.path.abspath”,例如:

savefile = os.path.abspath(Myinputfile)

when "Myinputfile" is a variable that contains the relative path and file name.当“Myinputfile”是一个包含相对路径和文件名的变量时。 For instance, derived from an argument define by the user.例如,派生自用户定义的参数。

But if you prefer to have absolute address of the folder, without file name try this:但是,如果您更喜欢文件夹的绝对地址,而没有文件名,请尝试以下操作:

saveloc = os.path.dirname(os.path.realpath(Myinputfile))

您可以使用pathlib查找所选文件的绝对路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM