【问题标题】:Python IOError: [Errno 13] Permission denied in linux?Python IOError:[Errno 13] linux 中的权限被拒绝?
【发布时间】:2020-04-27 18:43:38
【问题描述】:

我想将字符串字符写入文件,但出现类似IOError: [Errno 13] Permission denied: '/python/add.txt' 的错误。如何解决?

这是我的代码

q = open('/python/add.txt','r')
a = ['123', '234', '456']
lst = []
for line in q:
    for word in a:
        if word in line:
            line = line.replace(word + "\n",'')
    lst.append(line)
q.close()
z = open(r'/python/add.txt','w+')
for line in lst:
    z.write(line)
z.close()

【问题讨论】:

  • 更改文件的权限以便您可以写入。
  • 使用ls -l检查权限并使用chmod更改权限。
  • 这是我使用ls -l-rwxrwxrwx 1 root root 4497050 Apr 26 23:53 add.txt的文件权限
  • /python 的权限如何?您需要对目录具有“w”权限。
  • 我的目录权限drwxrwxrwx 3 root root 4096 Apr 18 07:42 python

标签: python linux debian


【解决方案1】:

您正试图在文件系统的根级别写入一个名为“python”的文件夹。这可能是不允许的。

我猜你不小心把/ 放在文件路径的开头(使其成为绝对路径),而你本来打算写"python/add.txt",这是一个相对文件路径。

您还应该在打开文件时使用with 构造,以确保它们之后被关闭。

使用with 语法和更好的变量名的更简洁的版本:


add_file_path = 'python/add.txt'
words_to_replace = ['123', '234', '456']
replaced_lines = []
with open(add_file_path, 'r') as f:
    for line in f:
        for word in words_to_replace:
            if word in line:
                line = line.replace(word + "\n",'')
        lst.append(line)

with open(add_file_path, 'w+') as f:
    for line in replaced_lines:
        f.write(line)

【讨论】:

  • 如果未找到使用python/addnew.txt 目录
  • 你需要弄清楚你想在哪里工作。我强烈建议不要在文件系统根级别的文件夹中工作(如“/python”)。您应该在当前工作目录中工作并使用相对路径。
  • 这里我使用一个shell脚本来执行文件,/bin/sh /python/filenew.sh然后在shell脚本中调用add.text文件然后循环来自add.text的数据并发送到python文件跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 2013-05-02
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多