简体   繁体   中英

using “With open” in python to write to another directory

I want to do the following:

1) Ask the user for input for a file path they wish a directory listing for. 2) Take this file path and enter the results, in a list, in a text file in the directory they input NOT the current directory.

I am very nearly there but the last step is that I can't seem to save the file to the directory the user has input only the current directory. I have set out the current code below (which works for the current directory). I have tried various variations to try and save it to the directory input by the user but to no avail - any help would be much appreciated.

CODE BELOW

import os

filenames = os.path.join(input('Please enter your file path: '))
with open ("files.txt", "w") as a:
    for path, subdirs, files in os.walk(str(filenames)):
       for filename in files:
         f = os.path.join(path, filename)
         a.write(str(f) + os.linesep)

You have to alter the with open ("files.txt", "w") as a: statement to not only include the filename, but also the path. This is where you should use os.path.join() . Id could be handy to first check the user input for existence with os.path.exists(filepath) .

os.path.join(input(...)) does not really make sense for the input , since it returns a single str , so there are no separate things to be joined.

import os

filepath = input('Please enter your file path: ')
if os.path.exists(filepath):
    with open (os.path.join(filepath, "files.txt"), "w") as a:
        for path, subdirs, files in os.walk(filepath):
            for filename in files:
                f = os.path.join(path, filename)
                a.write(f + os.linesep)

Notice that your file listing will always include a files.txt -entry, since the file is created before os.walk() gets the file list.

As ShadowRanger kindly points out, this LBYL (look before you leap) approach is unsafe, since the existence check could pass, although the file system is changed later while the process is running, leading to an exception.

The mentioned EAFP (it's easier to ask for forgiveness than permission) approach would use a try... except block to handle all errors.

This approach could look like this:

import os

filepath = input('Please enter your file path: ')
try:
    with open (os.path.join(filepath, "files.txt"), "w") as a:
        for path, subdirs, files in os.walk(filepath):
            for filename in files:
                f = os.path.join(path, filename)
                a.write(f + os.linesep)
except:
    print("Could not generate directory listing file.")

You should further refine it by catching specific exceptions . The more code is in the try block, the more errors unrelated to the directory reading and file writing are also caught and suppressed.

Move to the selected directory then do things.

Extra tip: In python 2 use raw_input to avoid special chars error like : or \\ ( just use input in python 3 )

import os

filenames = raw_input('Please enter your file path: ')
if not os.path.exists(filenames):
    print 'BAD PATH'
    return
os.chdir(filenames)
with open ("files.txt", "w") as a:
    for path, subdirs, files in os.walk('.'):
        for filename in files:
            f = os.path.join(path, filename)
            a.write(str(f) + os.linesep)

I came across this link https://cmdlinetips.com/2012/09/three-ways-to-write-text-to-a-file-in-python/ . I think your issue has something to do with you needing to provide the full path name and or the way you are using the close() method.

with open(out_filename, 'w') as out_file:
     .. 
     .. 
     .. parsed_line
     out_file.write(parsed_line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM