teaLeef
teaLeef

Reputation: 1989

Create a file in a directory using python

I am writing a python script in which I read a text file and I want to create a new text file in another directory. I wrote the following code:

def treatFiles(oldFile, newFile):   
    with open(oldFile) as old, open(newFile, 'w') as new:
        count = 0
        for line in old:
            count += 1
            if count%2 == 0:
                pass
            else:
                new.write(line)

if __name__ == '__main__':
    from sys import argv
    import os
    os.makedirs('NewFiles')
    new = '/NewFiles/' + argv[1]
    treatFiles(argv[1], new)

I tried running this code with a text file in the same directory than my python script, but got an error like

FileNotFoundError: [Errno 2] No such file or directory: '/NewFiles/testFile'

Apparently, it is not clear that NewFiles is a directory in which it should create the new file... How can I correct this?

Upvotes: 2

Views: 169

Answers (1)

Danica
Danica

Reputation: 28846

The problem is actually that in unix, /NewFiles/ means a folder in the root directory called NewFiles, not in the current directory. Remove the leading / and it should be fine.

Upvotes: 3

Related Questions