amac
amac

Reputation: 17

Python appending Files

I'm trying to do a loop and basically add a line to the end of the file. Although the loop works, it outputs all the files onto the desktop and doesn't modify the files. Additionally it deletes everything and just adds the contents of Vcomb in the files.

Cheers guys, i'm sure i'm doing something wrong here.

import os

print("Enter Date & Time: (YYYYMMDDhhmm)")
vdate = input()
vline = "VERIFY  48:0x"+vdate


print("Please Use: Verified by:___(Full name)____ on ___(Date)___")
vname = input()
vcomments = "       // " +vname

Vcomb = vline+vcomments
print (Vcomb)

print("Copy paste full directory path here")
directory = input()

for filename in os.listdir(directory):
    if filename.endswith(".ADC"):
        f = open(filename, 'a')
        f.write(Vcomb)
        f.close()

Upvotes: 0

Views: 43

Answers (1)

Strik3r
Strik3r

Reputation: 1057

The os.listdir() method will return just the filename but it will not have full path of the file. So every time you run, the program will create new files at the location from where you are running it.

For example if i have 3 files (a.txt,b.txt,c.txt) in my directory (D:\Data\Test), the os.listdir() will return just a.txt,b.txt,c.txt. So you need to add the directory path to it . Hope the below code will help you.

import os
print("Enter Date & Time: (YYYYMMDDhhmm)")
vdate = input()
vline = "VERIFY  48:0x"+vdate


print("Please Use: Verified by:___(Full name)____ on ___(Date)___")
vname = input()
vcomments = "       // " +vname

Vcomb = vline+vcomments
print (Vcomb)

print("Copy paste full directory path here")
directory = input()
print(directory)
for filename in os.listdir(directory):
    print(filename)
    if filename.endswith(".ADC"):
        f = open(os.path.join(directory, filename),'a')
        f.write(Vcomb)
        f.close()

Hope it helps !! Happy Coding :)

Upvotes: 2

Related Questions