[英]Python IOError: [Errno 13] Permission denied in linux?
I want to write string character to file, but i get error like this IOError: [Errno 13] Permission denied: '/python/add.txt'
.我想将字符串字符写入文件,但出现这样的错误
IOError: [Errno 13] Permission denied: '/python/add.txt'
。 how to solve this?如何解决这个问题?
this is my code这是我的代码
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()
You are trying to write into a folder called "python" at the root level of the filesystem.您正在尝试在文件系统的根级别写入一个名为“python”的文件夹。 This is likely not allowed.
这可能是不允许的。
I am guessing you have accidentally put a /
at the beginning of your file path (making it absolute), when you meant to write "python/add.txt"
, which is a relative file path.我猜你不小心在文件路径的开头放了一个
/
(使其成为绝对路径),当你打算写"python/add.txt"
时,这是一个相对文件路径。
You should also use the with
construct when opening files, to ensure they are closed afterwards.您还应该在打开文件时使用
with
构造,以确保它们在之后关闭。
Cleaner version using with
syntax and better variable names: 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.