python - 使用python重命名服务器上的文件

标签 python file-upload

我有这段代码,允许将文件上传到我网站上的特定目录,但是,我希望上传的每个文件(仅是 .txt 文件)都重命名为“equations.txt”,然后下载到我的计算机,然后从服务器删除。

例如,如果有人上传一个名为“test.txt”的文件,我需要上传该文件,然后在我的服务器上将其重命名为“equations.txt”。

到目前为止,我已经可以上传它了,但是当我添加以下行时:

os.renames('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'equations.txt')

它实际上完全删除了 /uploads/ 目录,而不是将目录中的文件重命名为“equations.txt”...代码如下:

#! /usr/bin/python

import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()

# Get filename here.
fileitem = form['filename']

# Test if the file was uploaded
if fileitem.filename:
   # strip leading path from file name to avoid 
   # directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   open('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'wb').write(fileitem.file.read())
   message = "The file " + fn + " was uploaded successfully"
   os.renames('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'equations.txt') ## Error line

else:
   message = "No file was uploaded"

print ("""\
Content-type: text/html\n\n
<html>
<body>
   <p>%s</p>
</body>
</html>
""") % (message)

如果没有上面添加的行,代码可以正常工作并将文件上传到 /uploads/ 目录。因此,在继续下一步之前,我需要重命名才能正常工作,谢谢。

最佳答案

您是否尝试过os.rename而不是os.renames

另外,尝试使用绝对路径作为目标。所以,这个:

dest_dir = '/home/xxxx/public_html/xxxx.com/test/uploads/'
os.rename(dest_dir + fn, dest_dir + 'equations.txt')

而不是这个:

os.renames('/home/xxxx/public_html/xxxx.com/test/uploads/' + fn, 'equations.txt')

关于python - 使用python重命名服务器上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16006255/

相关文章:

java - 如何检测文件类型的表单输入元素是否为空

jquery - 创建一个同时处理文件和 url 的 &lt;input&gt;?

python - 为什么从 Python 命令行调用 Python 时 Python 无法找到并运行我的脚本?

java - AWS Java putObject InvalidRedirectLocation

python - 尝试同时对两个数组进行排名

python - 无法安装 Pandas (错误 : Cannot uninstall 'numpy' )

cakephp - 如何在 CakePHP 中进行基于表单的文件上传?

php - exif 在移动设备上使用 php 上传图片时剥离 GPS header ?

python - 在healpy mollview中自定义颜色条

python - 仅外部加入 python pandas