Here is the code I've got:
filename = 'C:\\Users\chnyr\Desktop\Python Programs'
var = [i for i in open(filename, 'r+')]
['1\n', '2\n', '3\n', '\n']
I keep getting an error message below. I am using pyCharm v3.8.
C:\Users\chnyr\anaconda3\envs\untitled3\python.exe "C:/Users/chnyr/PycharmProjects/untitled3/translate test.py"
Traceback (most recent call last):
File "C:/Users/chnyr/PycharmProjects/untitled3/translate test.py", line 9, in <module>
var = [i for i in open('C:\\Users\chnyr\Desktop\Python Programs', 'r+')]
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\chnyr\\Desktop\\Python Programs'
Process finished with exit code 1
You get the error is you are trying to open a folder using the open() method. You can only open files with the method.
In python (and a lot of other languages) \ is the escape character.This makes coding with windows filesystems rather tricky. You have to escape each escape, by doing \\ instead of\. Aside from this, like Ann zen said, open only works with files. What you probably want is glob.glob, from the glob module.
import glob
var = [i for i in glob.glob('C:\\Users\\chnyr\\Desktop\\Python Programs\\*.py')]
print(var)
a = []
for i in var:
a.append(open(i,'r+'))
Related
I am learning to program in Python and am still at the very beginning.
I wrote a 2 scripts to cut out IP-addresses from a nmap-output.
The first script cuts out the IP-addresses:
import re
file = open("test.txt", "r")
ips = open("ips.txt", "w+")
for line in file:
ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', line)
if "filtered" in line:
ips.write(str(ip) + "\n")
This code works fine on Windows and Linux, but (I hope I'm right) the for-loop gets every line as a list. That means, my IP-addresses have the format ['x.x.x.x'].
I wrote a second script to delete all the unnecessary characters ([ ' and ]):
ip = open("ips.txt", "r")
ip_filtered = open("ip_filtered.txt", "w")
for line in ip:
s = line
neu = s.translate(({ord(i): None for i in '[\']'}))
ip_filtered.write(str(neu))
This script works well on Windows (I got a new file, just with IP-addresses), but on Linux I get the following error:
Traceback (most recent call last):
File "zeichen_loeschen.py", line 6, in <module>
neu = s.translate(({ord(i): None for i in '[\']'}))
TypeError: expected a string or other character buffer object
What's the reason for this error?
Thanks in advance :)
I get the same message when running with the python command on linux (which uses python 2.7). Try running it with the python3 command and your code should work.
Recently I found a program that cleans your folders. This is the coding.
import os
import shutil
lis=[]
destinationDir='C:\Users\Owner\All in two'
os.makedirs(destinationDir)
lis=os.listdir('C:\Users\Owner\My Documents')
for x in lis:
if x==__file__:
continue
shutil.move(x,destinationDir)
When I try to run it though, it gives an error saying:
Traceback (most recent call last):
File "C:\Users\Owner\Desktop\Cleaner.py", line 6, in <module>
lis=os.listdir('C:\Users\Owner\My Documents')
WindowsError: [Error 5] Access is denied: 'C:\\Users\\Owner\\My Documents/*.*'
I tried using cmd in admin but it failed.
All advice is appreciated.
Make sure you have the appropriate permissions on your computer!
Right click on the folder (My documents or a folder inside) and look in security, if you have all the permissions with a tick box in, then this error shouldn't occur!
Basically, if you're not admin or can't access my documents, then you can't run it!
Hope this helps XD
I am trying to find a specific pathname and pass this into os.chdir so I can run a command in that directory. I won't know the exact pathname hence why I have to run the find command. I have tried several ways to do this and each comes with a new error. The code below is one of the ways I have tried, can anyone suggest the best way to do this? Or how to fix this error?
Source Code:
import os
import subprocess
os.system('find ~ -path "*MyDir" > MyDir.txt')
output = subprocess.check_output("cat MyDir.txt", shell=True)
os.chdir(output)
os.system("file * > MyDir/File.txt")
The error:
Traceback (most recent call last):
File "sub1.py", line 8, in <module>
os.chdir(output)
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/MyhomeDir/Desktop/MyDir\n'
I know that directory exists and presume it has something to do with the b' and \n'. I just don't know what the problem is.
Get rid of the \n with strip:
output = subprocess.check_output("cat MyDir.txt", shell=True).strip()
os.chdir(output)
Is it possible to have a main Python process run as root, but then start a Python subprocess (multiprocessing) run as a different user? I also want that user's home directory and shell settings to apply just like if the Python interpreter had been started by that user.
Right now, when using os.setuid and gid, the permissions are correct, but the home directory is still incorrect as you'd expect:
>>> import os
>>> os.setgid(1000)
>>> os.setuid(1000)
>>> print os.getuid()
1000
>>> print os.getgid()
1000
>>> f = open('/etc/shadow')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 13] Permission denied: '/etc/shadow'
>>> os.system('echo $HOME')
/root
0
Any ideas?
Try:
os.environ['HOME'] = '/home/blah'
os.system("ls ~")
AFAIK, this is as good as you are likely to get, because installations with network home directories, or users with bash profiles that set HOME to wacky values aren't going to be replicable in pure Python, and could have side effects.
I have written the following really simple python script to change the desktop wallpaper on my mac (based on this thread):
from appscript import app, mactypes
import sys
fileName = sys.argv[1:]
app('Finder').desktop_picture.set(mactypes.File(fileName))
However when I run it I get the following output:
Traceback (most recent call last):
File "../Source/SetWallPaper2.py",
line 6, in
app('Finder').desktop_picture.set(mactypes.File(fileName))
File
"/Library/Python/2.5/site-packages/appscript-0.19.0-py2.5-macosx-10.5-i386.egg/appscript/reference.py", line 513, in call
appscript.reference.CommandError:
Command failed: OSERROR: -10000
MESSAGE: Apple event handler failed.
COMMAND:
app(u'/System/Library/CoreServices/Finder.app').desktop_picture.set(mactypes.File(u"/Users/Daniel/Pictures/['test.jpg']"))
I've done some web searching but I can't find anything to help me figure out what OSERROR -10000 means or how to resolve the issue.
fileName = sys.argv[1]
instead of
fileName = sys.argv[1:]
mactypes.File(u"/Users/Daniel/Pictures/['test.jpg']")
See the square brackets and quotes around the filename?