On 2/19/2023 2:31 PM, Chris Angelico wrote:
On Mon, 20 Feb 2023 at 06:24, Thomas Passin <li...@tompassin.net> wrote:

On 2/19/2023 1:53 PM, Chris Angelico wrote:
On Mon, 20 Feb 2023 at 03:41, Azizbek Khamdamov
<azizbek.khamda...@gmail.com> wrote:

Example 1 (works as expected)

file = open("D:\Programming\Python\working_with_files\cities.txt",
'r+') ## contains list cities

Side note: You happened to get lucky with P, w, and c, but for the
future, I recommend using forward slashes for your paths:

open("D:/Programming/Python/working_with_files/cities.txt", "r+")

Otherwise, you may run into annoying and hard-to-solve problems. Or
alternatively, you'll upgrade to a newer Python and start getting
warnings, which would at least tell you that there's a problem.

Or use r'...' strings.  If you are copying a path to clipboard from
Windows Explorer - a fairly common operation - it's much easier to
prepend the "r" than to change all the backslashes to forward slashes.


Yep, either way. I personally prefer using forward slashes since
there's no way to end an r-string with a single backslash, which is
often useful when building a path:

# won't work
path = r"c:\path\to\some\"
open(path + "file")

# will work
path = "c:/path/to/some/"
open(path + "file")

Never hit that one before. To be classified as "Learn something new every day"!

I've been using pathlib more lately.  It does clever things with "/" -

>>> from pathlib import PurePath
>>> p1 = PurePath('c:/this') / 'is' / 'a' /'test'
>>> p1
PureWindowsPath('c:/this/is/a/test')
# on Linux, would be a PurePosixPath

and also

>>> p2 = PurePath('c:/this/') /'is' /'a' /'test'
>>> p2
PureWindowsPath('c:/this/is/a/test')

Despite the apparent forward slashes, the right separators get used for the OS. And the Paths can be used with open(), etc.


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to