Linux Server / Python:OSError:[Errno 13]权限被拒绝

时间:2017-10-18 17:05:41

标签: python linux

我尝试用Python编写程序,它接受一些值,创建一个目录并将其添加到文本文件中供以后使用。我已将其上传到ubuntu VPS服务器,因为我打算稍后在我的网站上使用它。但是,每当我运行代码(下面)时,我都会收到以下错误:

Traceback (most recent call last):
  File "fileCreator.py", line 13, in <module>
    os.mkdir(dirName)
OSError: [Errno 13] Permission denied: 'just-a-test'

Python代码:

#!/usr/src
import os
from distutils.dir_util import copy_tree
import sys

title = raw_input("Blog Title: ")
dirName = title.replace(" ", "-").lower()

if os.path.isdir(dirName):
    print("Error: Directory Exists")
    sys.exit()
else:
    os.mkdir(dirName)

copy_tree("page", dirName)

def assignment(title, dirName ):
    desc = raw_input("Article Description: ")

    fo = open(dirName + "/txt-files/title.txt", "w")
    fo.write(title)
    fo.close()

    fo = open(dirName + "/txt-files/desc.txt", "w")
    fo.write(desc)
    fo.close()

    return None

assignment(title, dirName)
print("Done")

它存在某种权限错误,而且我已经看到了其他一些主题,但它们都没有产生解决方案。我对Linux命令并不过分精通,所以不要太熟悉!真的很感激帮助!

2 个答案:

答案 0 :(得分:1)

TLDR;使用Python脚本在目录中运行chmod 744

您对尝试创建文件夹的目录没有正确的权限。从您拥有fileCreator.py的同一目录,在命令行上运行ls -la .,它将输出如下内容:

drwxr-xr-x   9 user  staff   306 Oct  9 21:29 .
drwxr-xr-x+ 36 user  staff  1224 Sep 28 12:26 ..
-rw-r--r--   1 user  staff   977 Oct  9 21:04 .bashrc

可能还有很多其他文件。第一行是当前目录。 user是您的登录信息,staff是拥有它的组。它们在您的系统上会有所不同。 drwxr-xr-x是权限,它们由chmod命令更改。

在此处查看有关Linux权限的更多信息:https://www.linux.com/learn/understanding-linux-file-permissions

答案 1 :(得分:0)

import os

def create_assignment_directory(path):
    """
    create given path in local filesystem
    given path can be a relative, absolute path or
    path using tilde symbols like '~/folder_in_home_directory'

    prints absolute, normalized path for debugging purposes     
    """
    expanded_path = os.path.expanduser(path)
    normalized_path = os.path.abspath(expanded_path)

    print("create directory {0}".format(normalized_path))
    try:
        os.mkdir(expanded_path)
    except OSError as e:
        if e.errno == 17:  # errno.EEXIST
            print("directory {0} already exists.".format(normalized_path))
    else:
        print("successfully created directory {0}".format(normalized_path))

print("current working directory {0}".format(os.getcwd()))
create_assignment_directory("just-a-test")
create_assignment_directory("~/just-a-test")
create_assignment_directory("/tmp/just-a-test")