7

Im trying to create a random set of files from a list of file names in python 3.

#!/usr/local/bin/python3

import random
import sys

random.seed()

print("Reading lines from ", sys.argv[1])

linecount = 0
lines = []
with open(sys.argv[1]) as f:
    for line in f:
         lines.append(line)

filelist = random.sample(lines, 5);
for newfile in filelist:
    print("Touching file ", newfile)
    open(newfile.rstrip(), "a+")

This always fails for the first file with:

$ : ./file-gen.py files.txt
Reading lines from  files.txt
Touching file  62/6226320DE.pdf

Traceback (most recent call last):
  File "./file-gen.py", line 19, in <module>
    open(newfile.rstrip(), "a+");
FileNotFoundError: [Errno 2] No such file or directory: '62/6226320DE.pdf'

Any ideas what's missing?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
BetaRide
  • 16,207
  • 29
  • 99
  • 177

2 Answers2

7

I believe the problem is that the file mode a+ will create the file if its not present, but not the directory. You would have to write custom code to split the line of the filename from the path (or better still use os.path : https://docs.python.org/2/library/os.path.html, perhaps even os.path.dirname(path)

Have a look at: How to check if a directory exists and create it if necessary?

Be wary of security considerations of creating random paths in your system. Validating that the paths are inside a particular sandbox (consider someone putting an entry in your file of ../../ or /etc/passwd to get you to append random user data.. os.path.abspath can be useful - for this reason I am wary of pasting code which will just create random directories that you copy and paste in without considering that effect.

Community
  • 1
  • 1
Jmons
  • 1,766
  • 17
  • 28
0

I would suggest as a first step trying to open a specific file rather than a random set of files from the input to rule out permissions and path problems.

You should also try printing os.path.getcwd() to make sure that you have write permissions there.