Python: How to read multiple .NBT files and export to JSON? - python

I am a newbie when it comes to programming and i'm looking for a way to iterate through a directory filled with .NBT files and export them to JSON.
I know i can loop thorugh a directory using os.listdir, but i have trouble reading the files one by one and deciding what steps to take in order to get it to a JSON format.
The actual assignment is to loop through a bunch of .NBT files to see which Minecraft crate is faced towards with direction.
This is what i have now:
import python_nbt.nbt as nbt
import os
for file in os.listdir("Directory to nbt files"):
if file.endswith(".nbt"):
filename = nbt.read_from_nbt_file(file)
From here i get a FileNotFoundError saying there is no such file or directory.
What am i doing wrong?
And what must be done to continue?

you didn't specified the folder the file is in:
do nbt.read_from_nbt_file('Directory to nbt files' + '\\' + file)

Related

Copying files from one location of a server to another using python

Say I have a file that contains the different locations where some '.wav' files are present on a server. For example say the content of the text file location.txt containing the locations of the wav files is this
/home/user/test_audio_folder_1/audio1.wav
/home/user/test_audio_folder_2/audio2.wav
/home/user/test_audio_folder_3/audio3.wav
/home/user/test_audio_folder_4/audio4.wav
/home/user/test_audio_folder_5/audio5.wav
Now what I want to do is that I want to copy these files from different locations within the server to a particular directory within that server, for example say /home/user/final_audio_folder/ and this directory will contain all the audio files from audio1.wav to audio5.wav
I am trying to perform this task by using shutil, but the main problem with shutil that I am facing is that while copying the files, I need to name the file. I have written a demo version of what I am trying to do, but dont know how to scale it when I will be reading the paths of the '.wav' files from the txt file and copy them to my desired location using a loop.
My code for copying a single file goes as follows,
import shutil
original = r'/home/user/test_audio_folder_1/audio1.wav'
target=r'/home/user/final_audio_folder_1/final_audio1.wav'
shutil.copyfile(original,target)
Any suggestions will be really helpful. Thank you.
import shutil
i=0
with open(r'C:/Users/turing/Desktop/location.txt', "r") as infile:
for t in infile:
i+=1
x="audio"+str(i)+".wav"
t=t.rstrip('\n')
original= r'{}'.format(t)
target=r'C:/Users/turing/Desktop/audio_in/' + x
shutil.copyfile(original, target)
Use the built-in string's split() method within a for loop on the location.txt contents & split the name of the directory on the '/' character, then the last element in a new list would be your filename.

Python Unzipping files with different name to a different location

I am trying to extract the files from a zip archive and appending "EI" to each file inside it. I want these files to be extracted in a certain location. I'm new to python, hence unable to figure out.
for i in zip_list:
if ("Rally-EI" in i):
zipdata = zipfile.ZipFile(i)
zipinfos = zipdata.infolist()
for zipinfo in zipinfos:
zipinfo.filename = zipinfo.filename[:-4] + "_EI.txt"
zipdata.extract(zipinfo)
This is the code I'm using for appending the file name and it is working well. Need to extract these files to a specific location.
Thanks
Try using os.chdir() to change the current directory temporarily for this extraction. It's not the most efficient way, but, it will do the work.
Do save your current working directory using os.getcwd() to revert back to the original working directory after the extraction is done.

Python create a directory and save .txt file into it

I am currently working on the school assignment using the Python Socket library.
I have server.py and client.py, and basically, I request a copy of the .txt file from client-side to server-side, and client-side needed to receive the text elements, create a new .txt file and directory to save it.
I am stuck in the file handling on the client-side.
What is the best way I can do create a directory and save .txt file into it?
# create a new .txt file for incoming data and save to new directory
with open(new_dir / "copied_text_file.txt", '+w') as text:
text.write(file_text)
I tried this way, and it does not save in my new directory.
I appreciate your help, thank you!
If you are trying to create a path, use os.path methods, see in particular join.
Is the name of your new directory "new_dir"? If so the command needs to be open("new_dir/copied_text_file.txt", "+w"). If not and new_dir is a string of the directory use open((new_dir + "/copied_text_file.txt"), "+w") better yet would be to use os.path.join(new_dir, "copied_text_file.txt") and call open on the resulting pathname.
open() takes a string as the destination for the file you're going
to be working with. You can pass it a URI just like would would use
when working on the command line.
import os
with open(os.path.join(new_dir / "copied_text_file.txt", '+w')) as text:
text.write(file_text)
You could just concatenate with +,
with open(new_dir+'/'+ "copied_text_file.txt", '+w')) as text:
# ...
However, using + will be lower because path.join lives inside
complied c code the python interpreter has an easier time running,
rather than having to do the concatenation in python which has more
overhead than CPython models.
https://docs.python.org/3.5/library/os.path.html#os.path.join

Iterating over .wav files in subdirectories of parent directory

Cheers everybody,
I need help with something in python 3.6 exactly. So i have structure of data like this:
|main directory
| |subdirectory's(plural)
| | |.wav files
I'm currently working from a directory where main directory is placed so I don't need to specify paths before that. So firstly I wanna iterate over my main directory and find all subdirectorys. Then in each of them I wanna find the .wav files, and when done with processing them I wanna go to next subdirectory and so on until all of them are opened, and all .wav files are processed. Exactly what I wanna do with those .wav files is input them in my program, process them so i can convert them to numpy arrays, and then I convert that numpy array into some other object (working with tensorflow to be exact, and wanna convert to TF object). I wrote about the whole process if anybody has any fast advices on doing that too so why not.
I tried doing it with for loops like:
for subdirectorys in open(data_path, "r"):
for files in subdirectorys:
#doing some processing stuff with the file
The problem is that it always raises error 13, Permission denied showing on that data_path I gave him but when I go to properties there it seems okay and all permissions are fine.
I tried some other ways like with os.open or i replaced for loop with:
with open(data_path, "r") as data:
and it always raises permission denied error.
os.walk works in some way but it's not what I need, and when i tried to modify it id didn't give errors but it also didnt do anything.
Just to say I'm not any pro programmer in python so I may be missing an obvious thing but ehh, I'm here to ask and learn. I also saw a lot of similiar questions but they mainly focus on .txt files and not specificaly in my case so I need to ask it here.
Anyway thanks for help in advance.
Edit: If you want an example for glob (more sane), here it is:
from pathlib import Path
# The pattern "**" means all subdirectories recursively,
# with "*.wav" meaning all files with any name ending in ".wav".
for file in Path(data_path).glob("**/*.wav"):
if not file.is_file(): # Skip directories
continue
with open(file, "w") as f:
# do stuff
For more info see Path.glob() on the documentation. Glob patterns are a useful thing to know.
Previous answer:
Try using either glob or os.walk(). Here is an example for os.walk().
from os import walk, path
# Recursively walk the directory data_path
for root, _, files in walk(data_path):
# files is a list of files in the current root, so iterate them
for file in files:
# Skip the file if it is not *.wav
if not file.endswith(".wav"):
continue
# os.path.join() will create the path for the file
file = path.join(root, files)
# Do what you need with the file
# You can also use block context to open the files like this
with open(file, "w") as f: # "w" means permission to write. If reading, use "r"
# Do stuff
Note that you may be confused about what open() does. It opens a file for reading, writing, and appending. Directories are not files, and therefore cannot be opened.
I suggest that you Google for documentation and do more reading about the functions used. The documentation will help more than I can.
Another good answer explaining in more detail can be seen here.
import glob
import os
main = '/main_wavs'
wavs = [w for w in glob.glob(os.path.join(main, '*/*.wav')) if os.path.isfile(w)]
In terms of permissions on a path A/B/C... A, B and C must all be accessible. For files that means read permission. For directories, it means read and execute permissions (listing contents).

Opening .out files in Python

Am I right in thinking Python cannot open and read from .out files?
My application currently spits out a bunch of .out files that would be read manually for logging purposes, I'm building a Python script to automate this.
When the script gets to the following
for file in os.listdir(DIR_NAME):
if (file.endswith('.out')):
open(file)
The script blows up with the following error "IOError : No such file or directory: 'Filename.out' "
I've a similar function with the above code and works fine, only it reads .err files. Printing out DIR_NAME before the above code also shows the correct directory is being pointed to.
os.listdir() returns only filenames, not full paths. Use os.path.join() to create a full path:
for file in os.listdir(DIR_NAME):
if (file.endswith('.out')):
open(os.path.join(DIR_NAME, file))
As an alternative that I find a bit easier and flexible to use:
import glob,os
for outfile in glob.glob( os.path.join(DIR_NAME, '*.out') ):
open(outfile)
Glob will also accept things like '*/*.out' or '*something*.out'. I also read files of certain types and have found this to be very handy.

Categories