Windows vs Linux file modes - python

On a windows machine, I am trying to get a file's mode using the os module in python, like this (short snippet):
import os
from stat import *
file_stat = os.stat(path)
mode = file_stat[ST_MODE]
An example for the mode I got for a file is 33206.
My question is, how can I convert it to the linux-file mode method? (for example, 666).
Thanks to all repliers!
Edit:
found my answer down here :) for all who want to understand this topic further:
understanding and decoding the file mode value from stat function output

Check if this translates properly:
import os
import stat
file_stat = os.stat(path)
mode = file_stat[ST_MODE]
print oct(stat.S_IMODE(mode))
For your example:
>>>print oct(stat.S_IMODE(33206))
0666
Took it from here. Read for more explanation

One workaround would be to use:os.system(r'attrib –h –s d:\your_file.txt') where you can use the attribute switches :
R – This command will assign the “Read-Only” attribute to your selected files or folders.
H – This command will assign the “Hidden” attribute to your selected files or folders.
A – This command will prepare your selected files or folders for “Archiving.”
S – This command will change your selected files or folders by assigning the “System” attribute.

Related

Removing file permissions in python

I'm trying to remove file permissions in python. I am aware that the mode to do so is "000." However I'm seeing the removal of file permissions be done with flags as well such as "stat.S_IRWXO." Can anyone explain what I'm doing wrong
import os
import stat
file_path = 'random file'
os.chmod(file_path, stat.S_IRWXO)
My attempt with the "000" mode:
import os
import stat
file_path = "C:\Script\poop.txt"
os.chmod(file_path, 000)
EDIT
Using subprocesses, I was able to resolve the problem. I have not read the full documentation to know if chmod is not fully compatible with Windows, but it seems like it is at the very least, severely limited. Below is the code to use Window's "icacls" command to set permission. This is much more efficient.
import subprocess
file_path = r'C:\Script\poop.txt'
subprocess.check_output(['icacls.exe',file_path,'/deny','everyone:(f)'],stderr=subprocess.STDOUT)
SOURCES
calling windows' icacls from python
https://docs.python.org/2/library/os.html#os.chmod
This string:
file_path = "C:\Script\poop.txt"
is un-escaped. Thus the path becomes something like "C:Scriptpoop.txt". Use a raw string:
file_path = r"C:\Script\poop.txt"
or use \\ instead of \.
You can try to use subprocess module as an general solution:
import subprocess
file_path = 'file.txt'
subprocess.call(['chmod', '000', file_path])
terminal output ls -la:
-r--r--r-- 1 kernel 197121 0 Mar 8 10:29 file.txt
On ms-windows, you can only use os.chmod to set and remove the read-only bit. All others bits are ignored.
Basically, file permissions work differently on ms-windows than on POSIX operating systems. You will have to modify Access Control Lists using win32 API calls. To do that from within Python, you will need pywin32.

How do you define a local path in python

Good morning, I can indicate how to enter a path of internal hard disk in python, currently use the statement:
file = GETfile() or 'http://**********'
I would like to put a path to a local file, but it does not work, where am I wrong?
file = GETfile() or 'D:\xxx\xxxx\playlist\playlist.m3u'
\ is a escape character. You have three options.
1) use /. This, as a bonus works for linux as well:
'D:/xxx/xxxx/playlist/playlist.m3u'
2) escape the backslash
'D:\\xxx\\xxxx\\playlist\\playlist.m3u'
3) use raw strings:
r'D:\xxx\xxxx\playlist\playlist.m3u'
A correct answer is already given, but some additional information when working with local drive paths on Windows operating system.
Personally I would go with the r'D:\dir\subdir\filename.ext' format, however the other two methods already mentioned are valid as well.
Furthermore, file operations on Windows are limited by Explorer to a 256 character limit. Longer path names will usually result in an OS error.
However there is a workaround, by pre fixing "\\?\" to a long path.
Example of a path which does not work:
D:\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\filename.ext
Same file path which does work:
\\?\D:\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\reallyreallyreallyreallyreallylonglonglonglongdir\filename.ext
so the following code I use to change filenames to include the "\\?\":
import os
import platform
def full_path_windows(filepath):
if platform.system() == 'Windows':
if filepath[1:3] == ':\\':
return u'\\\\?\\' + os.path.normcase(filepath)
return os.path.normcase(filepath)
I use this for every path to file (or directories), it will return the path with a prefix. The path does not need to exist; so you can use this also before you create a file or directory, to ensure you are not running into the Windows Explorer limitations.
HTH

Find desktop folder in a custom location? [duplicate]

I have this small program and it needs to create a small .txt file in their 'My Documents' Folder. Here's the code I have for that:
textfile=open('C:\Users\MYNAME\Documents','w')
lines=['stuff goes here']
textfile.writelines(lines)
textfile.close()
The problem is that if other people use it, how do I change the MYNAME to their account name?
Use os.path.expanduser(path), see http://docs.python.org/library/os.path.html
e.g. expanduser('~/filename')
This works on both Unix and Windows, according to the docs.
Edit: forward slash due to Sven's comment.
This works without any extra libs:
import ctypes.wintypes
CSIDL_PERSONAL = 5 # My Documents
SHGFP_TYPE_CURRENT = 0 # Get current, not default value
buf= ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_PERSONAL, None, SHGFP_TYPE_CURRENT, buf)
print(buf.value)
Also works if documents location and/or default save location is changed by user.
On Windows, you can use something similar what is shown in the accepted answer to the question: Python, get windows special folders for currently logged-in user.
For the My Documents folder path, useshellcon.CSIDL_PERSONALin the shell.SHGetFolderPath() function call instead of shellcon.CSIDL_MYPICTURES.
So, assuming you have the PyWin32 extensions1 installed, this might work (see caveat in Update section below):
>>> from win32com.shell import shell, shellcon
>>> shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0)
u'<path\\to\\folder>'
Update: I just read something that said that CSIDL_PERSONAL won't return the correct folder if the user has changed the default save folder in the Win7 Documents library. This is referring to what you can do in library's Properties dialog:
The checkmark means that the path is set as the default save location.
I currently am unware of a way to call the SHLoadLibraryFromKnownFolder() function through PyWin32 (there currently isn't a shell.SHLoadLibraryFromKnownFolder. However it should be possible to do so using the ctypes module.
1Installers for the latest versions of the Python for Windows Extensions are currently available from: http://sourceforge.net/projects/pywin32

os.listdir can't see my directory

I am working on a python script that installs an 802.1x certificate on a Windows 8.1 machine. This script works fine on Windows 8 and Windows XP (haven't tried it on other machines).
I have isolated the issue. It has to do with clearing out the folder
"C:\Windows\system32\config\systemprofile\AppData\LocalLow\Microsoft\CryptURLCache\Content"
The problem is that I am using the module os and the command listdir on this folder to delete each file in it. However, listdir errors, saying the folder does not exist, when it does indeed exist.
The issue seems to be that os.listdir cannot see the LocalLow folder. If I make a two line script:
import os
os.listdir("C:\Windows\System32\config\systemprofile\AppData")
It shows the following result:
['Local', 'Roaming']
As you can see, LocalLow is missing.
I thought it might be a permissions issue, but I am having serious trouble figuring out what a next step might be. I am running the process as an administrator from the command line, and it simply doesn't see the folder.
Thanks in advance!
Edit: changing the string to r"C:\Windows\System32\config\systemprofile\AppData", "C:\Windows\System32\config\systemprofile\AppData", or C:/Windows/System32/config/systemprofile/AppData" all produce identical results
Edit: Another unusual wrinkle in this issue: If I manually create a new directory in that location I am unable to see it through os.listdir either. In addition, I cannot browse to the LocalLow or my New Folder through the "Save As.." command in Notepad++
I'm starting to think this is a bug in Windows 8.1 preview.
I encountered this issue recently.
I found it's caused by Windows file system redirector
and you can check out following python snippet
import ctypes
class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)
#Example usage
import os
path = 'C:\\Windows\\System32\\config\\systemprofile\\AppData'
print os.listdir(path)
with disable_file_system_redirection():
print os.listdir(path)
print os.listdir(path)
ref : http://code.activestate.com/recipes/578035-disable-file-system-redirector/
You must have escape sequences in your path. You should use a raw string for file/directory paths:
# By putting the 'r' at the start, I make this string a raw string
# Raw strings do not process escape sequences
r"C:\path\to\file"
or put the slashes the other way:
"C:/path/to/file"
or escape the slashes:
# You probably won't want this method because it makes your paths huge
# I just listed it because it *does* work
"C:\\path\\to\\file"
I'm curious as to how you are able to list the contents with those two lines. You are using escape sequences \W, \S, \c, \s, \A in your code. Try escaping the back slash like this:
import os
os.listdir('C:\\Windows\\System32\\config\\systemprofile\\AppData')

Finding the user's "My Documents" path

I have this small program and it needs to create a small .txt file in their 'My Documents' Folder. Here's the code I have for that:
textfile=open('C:\Users\MYNAME\Documents','w')
lines=['stuff goes here']
textfile.writelines(lines)
textfile.close()
The problem is that if other people use it, how do I change the MYNAME to their account name?
Use os.path.expanduser(path), see http://docs.python.org/library/os.path.html
e.g. expanduser('~/filename')
This works on both Unix and Windows, according to the docs.
Edit: forward slash due to Sven's comment.
This works without any extra libs:
import ctypes.wintypes
CSIDL_PERSONAL = 5 # My Documents
SHGFP_TYPE_CURRENT = 0 # Get current, not default value
buf= ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_PERSONAL, None, SHGFP_TYPE_CURRENT, buf)
print(buf.value)
Also works if documents location and/or default save location is changed by user.
On Windows, you can use something similar what is shown in the accepted answer to the question: Python, get windows special folders for currently logged-in user.
For the My Documents folder path, useshellcon.CSIDL_PERSONALin the shell.SHGetFolderPath() function call instead of shellcon.CSIDL_MYPICTURES.
So, assuming you have the PyWin32 extensions1 installed, this might work (see caveat in Update section below):
>>> from win32com.shell import shell, shellcon
>>> shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0)
u'<path\\to\\folder>'
Update: I just read something that said that CSIDL_PERSONAL won't return the correct folder if the user has changed the default save folder in the Win7 Documents library. This is referring to what you can do in library's Properties dialog:
The checkmark means that the path is set as the default save location.
I currently am unware of a way to call the SHLoadLibraryFromKnownFolder() function through PyWin32 (there currently isn't a shell.SHLoadLibraryFromKnownFolder. However it should be possible to do so using the ctypes module.
1Installers for the latest versions of the Python for Windows Extensions are currently available from: http://sourceforge.net/projects/pywin32

Categories