我有这段代码,允许将文件上传到我网站上的特定目录,但是,我希望上传的每个文件(仅是 .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/