Python Forum
does not save in other path than opened files before
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
does not save in other path than opened files before
#1
Hi,
sorry for my poor title description.
I am rather new to python and programming, but read some tutorials and books about simple string manipulations and file handly already.

Pre-infomation: I know, I have a rather old version of python (3.7.9), because it came with Thonny (3.3.13) and I do not know, if it would work, if I just would copy a newer into the Thonny directory.
Further I run this (thonny) on a Windows 10. (European keyboard code page [German, codepage 1252])
(Can't just test my code on Linux or Mac)

My problem is, that I get error messages, when trying to save to another/ subdirectory, when opened for reading another, before. (writing to new files in same directory with new file name or to script.py-projects-folder ("bla.txt") works normal)

>>> %Run check.py
Traceback (most recent call last):
  File "C:\Users\Alex\Documents\PYT\check.py", line 4, in <module>
    g = open ("D:\MOC\extraced\LowerDir\Doc.txt", "w")
OSError: [Errno 22] Invalid argument: '"D:\MOC\extraced\LowerDir\\Doc.txt'
bytheway: alternate saving directory: OSError: [Errno 22] Invalid argument: 'D:\otherFolder\\Doc.txt'

Also one time I found another message: OSError: [Errno 22] Invalid argument: 'D:\\MOC\\extraced\LowerDir\\Doc.txt' - which even does not fit to my code g = open ("D:\MOC\extraced\LowerDir\Doc.txt", "w") above.
OK, I know, python or Windows could not open such file path. But why does it alternate those strings in such a strange way by itself?

Annotation: I copied the error messages by clipboard from Thonny - Shell window (from Windows terminal console are the same). The single or double backslashes in my python code and the output messages are exactly copied form the error messages and not altered!
I have 'D:\other\Doc.txt' in my code, and python answers with 'D:\other\\Doc.txt', which logically fails.

My code:
f =     open ("D:\MOC\extraced\Document.txt", "r")
# g = open ("D:\MOC\extraced\Document_3_bla.txt", "w") only # this code works properly
# g = open ("D:\MOC\extraced\LowerDir\Doc.txt", "w") #  this does not work - even if subDir exists or not
g =    open ("C:\anyOtherPathOnMyHDD\outputfile.txt", "w") # this does not work either. (C:\bla is not restricted and it does not matter if  C:\path does exist before or not. Also other Partitons D:, E:, G: do not work better. It seems to be the different path from opening)

text = f.read()
newtext = bla(text) # string alternation in functions
g.write (newtext)
g.flush() #  do not know, if really necessary
g.close()
f.close()
OK, there is my old version of python.
But saving to different (sub)folders should work with older versions, too -doesn't it?.
Saving into the same directory with other filename or creating new files witout reading before just works fine.
Also I guess I typed the backslashes correctly in my code, because saving to different filenames works D:\bla\fname2.txt and I only added a subDirName between them. D:\bla\blub\fname.txt
How can python internally change the path "C:\bla\blubb\file.txt" to 'C:\\bla\blubb\\file.txt' ???
Only saving to my python code files directory (without folder names, e.g. f= open("HelloThere.txt", "w") works either without problems and prpperly gerenrates files in this project folder.) (and saving to "opened before" directories, like above)

What do I wrong? (windows code page is set, no foreign characters in filenames and folder names; backslashes as character 0x5C ). I have no further clue.

Thank you!
Reply
#2
(Jun-23-2023, 03:49 PM)icode Wrote: Thonny (3.3.13) and I do not know
Get a new version of Thonny it's comes with Python 3.10 built in.

Do not use singel \ in Path for Windows,because of escape characters.
Here you clearly see the problem.
>>> f = "C:\anyOtherPathOnMyHDD\outputfile.txt"
>>> f
'C:\x07nyOtherPathOnMyHDD\\outputfile.txt'
So raw string r or just turn around / work fine.
>>> f =  r"C:\anyOtherPathOnMyHDD\outputfile.txt"
>>> f
'C:\\anyOtherPathOnMyHDD\\outputfile.txt'
>>> 
>>> f =  "C:/anyOtherPathOnMyHDD/outputfile.txt"
>>> f
'C:/anyOtherPathOnMyHDD/outputfile.txt'
The basic of open and write files,and use with open then do not need to close file.
with open(r'G:\div_code\hello.txt') as fp:
    result = fp.read()
    print(result)

# Add 123 to hello world
with open(r'G:\div_code\new_hello.txt', 'w') as fp_out:
    add_numb = f'{result} 123'
    fp_out.write(add_numb)
Output:
hello world

hello.txt:
Output:
hello world
new_hello.txt:
Output:
hello world 123
Reply
#3
oha, RAW-String,

yes, Michael Kofler did mention that to "strings" in his book (p.86, 1rd ed), and I used this behaviour several times yet, (e.g. \"), but I did not think of that when I typed those path variables for file handling. (But, indeed, sometimes it could be necessary to set/mask special chars into file or folder names)

I decided against the with-proceeding due I wanted to open and close the files seperately, independend of enclosed code commands between.
Of course the with command is more comfortable and avoids misstakes.

Many thanks.

But anyhow it worked when I was loading a file witout mourning, but first when I wanted to save them in a subdirectory, I got those problems. I am still not understanding this.
Reply
#4
(Jun-23-2023, 06:01 PM)icode Wrote: But anyhow it worked when I was loading a file witout mourning, but first when I wanted to save them in a subdirectory, I got those problems. I am still not understanding this.
It should give you clear error messags if path dos not exsist.
with open(r'G:\div_code\egg\new.txt', 'w') as fp_out:
    fp_out.write('hello')
Error:
Traceback (most recent call last): File "<module1>", line 2, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'G:\\div_code\\egg\\new.txt'
So in this case i have no folder egg,can make the folder and eg use pathlib a more modern to deal with filesystem and paths.
from pathlib import Path

file_path = Path("G:/div_code/egg/hello.txt")
file_path.parent.mkdir(parents=True, exist_ok=True)
with file_path.open('w', encoding="utf-8") as fp_out:
    fp_out.write('hello')
So no error messages folder egg has been created and file hello.txt is in Path G:/div_code/egg.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to save to multiple locations during save cubangt 1 560 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  change directory of save of python files akbarza 3 900 Jul-23-2023, 08:30 AM
Last Post: Gribouillis
  How to save files in a separate directory Scordomaniac 3 1,901 Mar-16-2022, 10:17 AM
Last Post: Gribouillis
Question How to get html information from a tab of my default browser opened with webbrowser? noahverner1995 2 4,511 Jan-14-2022, 10:02 AM
Last Post: noahverner1995
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,222 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  get all the files in the path in a list? korenron 23 7,118 Jul-19-2021, 07:44 AM
Last Post: korenron
  Rmarkdown opened by python code - errors Rav013 0 2,096 Apr-27-2021, 03:13 PM
Last Post: Rav013
  How to get full path of specified hidden files matching pattern recursively SriRajesh 4 3,951 Jan-18-2020, 07:12 PM
Last Post: SriRajesh
  Downloading And Saving Zip Files To A Particular Path Folder eddywinch82 2 2,574 Jan-06-2020, 07:56 PM
Last Post: eddywinch82
  Details of attachment files in a msg file such as file names save into a python list klllmmm 2 5,726 Nov-12-2019, 05:59 AM
Last Post: klllmmm

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020