Unpredictable results from os.path.join in windows

风流意气都作罢 提交于 2019-12-11 07:07:17

问题


So what I'm trying to do is to join something in the form of

os.path.join('C:\path\to\folder', 'filename'). 

**edit : Actual code is :

filename = 'creepy_%s.pcl' % identifier
file = open(os.path.join(self.cache_dir, filename), 'w')

where self.cache_dir is read from a file using configobj (returns string) and in the particular case is '\Documents and Settings\Administrator\creepy\cache'

The first part is returned from a configuration file, using configobj. The second is a concatenation of 2 strings like: 'file%s' % name

When I run the application through the console in windows using the python interpreter installed, I get the expected result which is

C:\\path\\to\\folder\\filename 

When I bundle the same application and the python interpreter (same version, 2.6) in an executable in windows and run the app the result is instead

C:\\path\\to\\folderfilename

Any clues as to what might be the problem, or what would cause such inconsistencies in the output ?


回答1:


Your code is malformed. You need to double those backslashes or use a raw string.

os.path.join('C:\\path\\to\\folder', 'filename'). 

I don't know why it works in one interpreter and not the other but your code will not be interpreted properly as is. The weird thing is i'd have expected a different output, ie: C:pathtofolder\filename.




回答2:


It is surprising behavior. There is no reason it should behave in such a way.

Just be be cautious, you can change the line to the following.

os.path.join(r'C:\path\to\folder\', 'filename'). 

Note the r'' raw string and the final \




回答3:


Three things you can do:

  1. Use double-slashes in your original string, 'C:\\path\\to\\folder'

  2. Use a raw string, r'C:\path\to\folder'

  3. Use forward-slashes, 'C:/path/to/folder'




回答4:


I figure it out yesterday. As usual when things seem really strange, the explanation is very simple and most of the times involve you being stupid.

To cut a long story short there were leftovers from some previous installations in dist-packages. The bundled interpreter loaded the module from there , but when i ran the python script from the terminal , the module (newer version) in the current dir was loaded. Hence the "unpredictable" results.



来源:https://stackoverflow.com/questions/4982105/unpredictable-results-from-os-path-join-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!