Creating empty text files with specific names in a directory - python

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.

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

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()

Related

Copying/pasting specific files in batch from one folder to another

I'am really new to this python scripting thing, but pretty sure, that there is the way to copy files from one folder (via given path in .txt file) to another.
there would be directly path to the folder, which contains photo files
I'am working with huge amounts of photos, which contains gps metadata (so i need not to lose it).
Really apreciate any help, thanks.
Here is a short and simple solution:
import shutil
import os
# replace file_list.txt with your files
file_list = open("file_list.txt", "r")
# replace my_dir with your copy dir
copy_dir = "my_dir"
for f in file_list.read().splitlines():
print(f"copying file: {f}")
shutil.copyfile(f, f"{copy_dir}/{os.path.split(f)[1]}")
file_list.close()
print("done")
It loops over all the files in the file list, and copies them. It should be fast enough.

Opening multiple json files inside a for loop

I have some code that saves a json file and prints it to screen. I am trying to find the best way to iterate through a directory of files, printing one file after another, but I am receiving an '[Errno 13] Permission Denied' error.
At present I am doing the following:
json_path = 'MYPATH'
json_files = [f for f in os.listdir(json_path) if f.endswith('.json')]
for jf in json_files:
with open (os.path.join(json_path)) as my_jf:
json_text = json.load(my_jf)
print(json_text)
I have made sure that the folder in the path is not opened elsewhere, and I have access to it. If there is a simpler way to achieve this I would appreciate the input.
You are not really open the files, you are opening the path where the files are located.
You could try to change:
with open (os.path.join(json_files)) as my_jf:
I have stumbled across an answer of sorts. If I create a list of the text files in the directory the json.load request seems to work:
my files = ['file1.txt', 'file2.txt']
for file in myfiles:
with open(file) as json_file:
jsonconvo = json.load(json_file)
print(jsonconvo)
I'm unsure if I've necessarily overcome the the actual issue, but this seems like a reasonable workaround.
Looks like you just forgot to actually include the file name in your open() statement:
with open(os.path.join(json_path, jf)) as my_jf:

How do I delete multiple files in a folder?

I wanted to ask the forum how can I delete multiple files in a folder using Python. I tried using the import os module along with os.unlink() module, but it doesn't work. Any help would be greatly appreciated.
Most likely it's because the filename used in the os.unlink(filename) isn't a full path to the file (os.listdir() just returns a sequence of filenames). You probably need to use os.path.join() to prefix the 'c:\\users\\user1' folder to it first.
Something along these lines:
import os
folder = 'c:\\users\\user1\\Pictures'
for filename in os.listdir(folder):
if filename.endswith('.txt'):
os.unlink(os.path.join(folder, filename))

Write multiple text files to the directory in Python

I was working on saving text to different files. so, now I already created several files and each text file has some texts/paragraph in it. Now, I just want to save these files to a directory. I already created a self-defined directory, but now it is empty. I want to save these text files into my directory.
The partial code is below:
for doc in root:
docID = doc.find('DOCID').text.strip()
text = doc.find('TEXT').text,strip()
f = open("%s" %docID, 'w')
f.write(str(text))
Now, I created all the files with text in it. and I also have a blank folder/directory now. I just don't know how to put these files into the directory.
I would be appreciate it.
========================================================================
[Solved] Thank you guys for your all helping! I figured it out. I just edit my summary here. I got a few problems.
1. my docID was saved as tuple. I need to convert to string without any extra symbol. here is the reference i used: https://stackoverflow.com/a/17426417/9387211
2. I just created a new path and write the text to it. i used this method: https://stackoverflow.com/a/8024254/9387211
Now, I can share my updated code and there is no more problem here. Thanks everyone again!
for doc in root:
docID = doc.find('DOCID').text.strip()
did = ''.join(map(str,docID))
text = doc.find('TEXT').text,strip()
txt = ''.join(map(str,docID))
filename = os.path.join(dst_folder_path, did)
f = open(filename, 'w')
f.write(str(text))
Suppose you have all the text files in home directory (~/) and you want to move them to /path/to/dir folder.
from shutil import copyfile
import os
docid_list = ['docid-1', 'docid-2']
for did in docid_list:
copyfile(did, /path/to/folder)
os.remove(did)
It will copy the docid files in /path/to/folder path and remove the files from the home directory (assuming you run this operation from home dir)
You can frame the file path for open like
doc_file = open(<file path>, 'w')

Load files from a list of file paths in python

I have a text file with a couple hundred file paths to text files which I would like to open, write / cut up pieces from it and save under a new name.
I've been Googling how to do this and found the module glob, but I can't figure out exactly how to use this.
Could you guys point me in the right direction?
If you have specific paths to files, you won't need to glob module. The glob module is useful when you want to use path like /user/home/someone/pictures/*.jpg. From what I understand you have a file with normal paths.
You can use this code as a start:
with open('file_with_paths', 'r') as paths_list:
for file_path in paths_list:
with open(file_path, 'r') as file:
# Do what you want with one of the files here.
You can just traverse the file line by line and then take out what you want from that name. Later save/create it . Below sample code might help
with open('file_name') as f:
for file_path in f:
import os
file_name = os.path.basename(file_path)
absolute path = os.path.dirname(file_path)
# change whatever you want to with above two and save the file
# os.makedirs to create directry
# os.open() in write mode to create the file
Let me know if it helps you

Categories

Resources