0

I have two directories:

dir = path/to/annotations

and

dir_img = path/to/images

The format of image names in dir_img is image_name.jpg.

I need to create empty text files in dir as: image_name.txt, wherein I can later store annotations corresponding to the images. I am using Python.

I don't know how to proceed. Any help is highly appreciated. Thanks.

[Edit]: I tried the answer given here. It ran without any error but didn't create any files either.

Rahul Bohare
  • 762
  • 2
  • 11
  • 31

2 Answers2

3

This should create empty files for you and then you can proceed further.

import os
for f in os.listdir(source_dir):
    if f.endswith('.jpg'):
        file_path = os.path.join(target_dir, f.replace('.jpg', '.txt'))
        with open(file_path, "w+"):
            pass
j_4321
  • 15,431
  • 3
  • 34
  • 61
Sadanand Upase
  • 132
  • 1
  • 15
  • Pardon me for not knowing the subtleties but isn't this the same answer as @Elias? Anyway, still there is no file created. – Rahul Bohare Oct 24 '17 at 09:25
  • yes. I should have had a look there. You need to provide more details i think about environment where you are running this script. Is there any error you are getting? Otherwise there is no reason why this script should not work. – Sadanand Upase Oct 24 '17 at 09:32
  • I am working on Linux 8.5 based OS, Jessie. The code runs without throwing any error. I also checked that I do have write privileges for the `target_dir`. – Rahul Bohare Oct 24 '17 at 09:39
  • It worked. Turns out the mistake was on my side; I was using incorrect path. Thanks for your help. – Rahul Bohare Oct 24 '17 at 09:50
1

You can use the module os to list the existing files, and then just open the file in mode w+ which will create the file even if you're not writing anything into it. Don't forget to close your file!

import os
for f in os.listdir(source_dir):
    if f.endswith('.jpg'):
        open(os.path.join(target_dir, f.replace('.jpg', '.txt')), 'w+').close()
Elias Mi
  • 611
  • 6
  • 14