import sys
filepath = "D:\\Desktop\\SIGN IN OUT\\"
times = ["min.txt","hour.txt","datein.txt","dateout.txt"]
while True:
    z = input("Enter Your First and Last Name. Just don't put a . in your name. : ")
    y = z+'\\'+z
    for x in range(len(times)):
        f = open(filepath+y+times[x],'w')
        f.write('0')
        f.close()
            Asked
            
        
        
            Active
            
        
            Viewed 57 times
        
    0
            
            
        - 
                    3Are you getting any specific errors? What exactly is making file creation 'not work'? – HunterM267 Jul 25 '17 at 21:17
2 Answers
3
            
            
        Joining files with \\ is not the best way to do it. The recommended way is using os.path.join from the os module:
import os
while True:
    z = input("Enter Your First and Last Name. Just don't put a . in your name. : ")
    y = os.path.join(*z.split())
    for x in times:
        with open(os.path.join(filepath, y, x), 'w') as f:
            f.write('0')
I also recommend -
- Using a context manager to handle your files, it makes your code cleaner. 
- Iterating over - timesdirectly rather than the indices
Also, as Jean-François Fabre states in his answer, you'd better use os.mkdir to create any directories that don't exist before you create files in them. Here's a good reference.
 
    
    
        cs95
        
- 379,657
- 97
- 704
- 746
- 
                    1Is it worth mentioning the choice of doing `for x in times:` instead of the range, as well? – Simon Fraser Jul 25 '17 at 21:18
- 
                    
- 
                    1@cᴏʟᴅsᴘᴇᴇᴅ that doesn't fix OP's error like _at all_. It's rather a "code review" answer. The issue is still there because `y` path part doesn't exist, since the user just entered it – Jean-François Fabre Jul 25 '17 at 21:23
- 
                    @Jean-FrançoisFabre Good point. I would up vote your answer but I've Voxxed myself. Anyway, I've mentioned it as a footnote. Won't duplicate because you've already said it :) – cs95 Jul 25 '17 at 21:24
2
            
            
        the problem is that in that code:
z = input("Enter Your First and Last Name. Just don't put a . in your name. : ")
y = z+'\\'+z
- yis two times the same value, joined by- \\(won't give you the directories you're expecting, but that's not the main issue)
- but when trying to open your file, you're doing that in a directory that probably doesn't exist.
So you'll have to add (using os.path.join is cleaner as @COLDSPEED noted):
my_dir = os.path.join(filepath, y)
if not os.path.isdir(my_dir):
    os.makedirs(my_dir)  # creates dirs if doesn't exist, with full path
before opening your files so the directory supposed to contain them exists (open fails if the directory doesn't exist)
 
    
    
        Jean-François Fabre
        
- 137,073
- 23
- 153
- 219
