0

I have the path of a directory workdir, and I would like to save a text file into it, then append text to that text file.

My code to append to the text file works fine, but I am struggling with the initial step of dropping my text file into the workdir.

Here is my code:

workdirpath = os.path.dirname(self.finfo.local_file_path)
for file in glob(workdirpath):
    with open(f"{workdir}.txt", 'w') as f:
    f.write(page.text)

I'm not sure what the glob function does but I don't think it is relavent.

The above code simply creates a file in the same working directory as the workdir, but I want the file to be inside workdir!

jikf
  • 25
  • 6

2 Answers2

0

for file in glob(workdirpath) here is not relevant - you use it when you want to do something for each file in directory.

Your problem is that you have wrong filename - f"{workdir}.txt" is file with same name as folder, not file inside folder. Try something like f"{workdirpath}/filename.txt. Slash / means file is inside directory.

So simplest probably would be:

workdirpath = os.path.dirname(self.finfo.local_file_path)
with open(f"{workdirpath}/filename.txt", 'w+') as f:
    f.write(page.text)

However to deal with differences between platforms and to check if directory exists it's good to use pathlib, which is installed together with python by default. With pathlib:

from pathlib import Path

# Get directory.
workdirpath = Path(self.finfo.local_file_path)

# Only proceed if it's directory and it exists.
if workdirpath.is_dir():
   filepath = workdirpath / "filename.txt" # / operator combines Paths.

   # Open (create) file for writing.
   with filepath.open("w+", encoding ="utf-8") as f:
      f.write(page.text)
Matija Sirk
  • 596
  • 2
  • 15
0

Is this within scope?

a = "/path/to/workdir/"
with open(f"{a}myfile.txt", 'w+') as f:
    f.write(page.text)

The w+ simply creates the file if it doesn't already exist. Just remove the + if you're sure the file will always exist.

Fnatical
  • 506
  • 5
  • 7
  • 1
    `w` is also fine and creates the file if it doesn't exist. The use of `w+` is to open the file for both writing *and* reading: https://stackoverflow.com/questions/1466000/difference-between-modes-a-a-w-w-and-r-in-built-in-open-function – slothrop Apr 19 '23 at 13:04