Python create a directory and save .txt file into it - python

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

Related

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

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)

How to have multiple programs access the same file without manually giving them all the file path?

I'm writing several related python programs that need to access the same file however, this file will be updated/replaced intermittently and I need them all to access the new file. My current idea is to have a specific folder where the latest file is placed whenever it needs to be replaced and was curious how I could have python select whatever text file is in the folder.
Or, would I be better off creating a program that has a Class entirely dedicated to holding the information of the file and have each program reference the file in that class. I could have the Class use tkinter.filedialog to select a new file whenever necessary and perhaps have a text file that has the path or name to the file that I need to access and have the other programs reference that.
Edit: I don't need to write to the file at all just read from it. However, I would like to have it so that I do not need to manually update the path to the file every time I run the program or update the file path.
Edit2: Changed title to suit the question more
If the requirement is to get the most recently modified file in a specific directory:
import os
mypath = r'C:\path\to\wherever'
myfiles = [(f,os.stat(os.path.join(mypath,f)).st_mtime) for f in os.listdir(mypath)]
mysortedfiles = sorted(myfiles,key=lambda x: x[1],reverse=True)
print('Most recently updated: %s'%mysortedfiles[0][0])
Basically, get a list of files in the directory, together with their modified time as a list of tuples, sort on modified date, then get the one you want.
It sounds like you're looking for a singleton pattern, which is a neat way of hiding a lot of logic into an 'only one instance' object.
This means the logic for identifying, retrieving, and delivering the file is all in one place, and your programs interact with it by saying 'give me the one instance of that thing'. If you need to alter how it identifies, retrieves, or delivers what that one thing is, you can keep that hidden.
It's worth noting that the singleton pattern can be considered an antipattern as it's a form of global state, it depends on the context of the program if this is a deal breaker or not.
To "have python select whatever text file is in the folder", you could use the glob library to get a list of file(s) in the directory, see: https://docs.python.org/2/library/glob.html
You can also use os.listdir() to list all of the files in a directory, without matching pattern names.
Then, open() and read() whatever file or files you find in that directory.

Is it able to create folders with Python?

I am writing a Pokemon game and I want to make folders to save different types of Pokemon, as well as other sorts of information, in. I want to use folders because it would be really messy if I were to save all my data into a single file.
Is it possible to create folders with a Python program? This would make it easier and cleaner for me when I try to import the Pokemon data from external websites.
You can use open with the a mode, which opens a file in append mode, and creates it if it does not exist:
my_file = open('file.txt', 'a')
# Optionally: write stuff to my_file, using my_file.write('stuff')
my_file.close()
You can run any command that you want with python by doing:
import os
os.popen("mkdir random_name") # This creates a directory called "random_name"
os.popen("touch rando_name.txt") # This creates a file called "random_name"
You can run any command that you would usually run in terminal inside the popen.
You can use the popen() command in both UNIX(Linux, macOS) as well as Windows OS.
You can learn more regarding this by taking a look in the python documentation.
https://docs.python.org/2/library/subprocess.html
If you'd like to create folders (or directories), you need os.mkdir:
import os
os.mkdir("folder_name")
To create some deep folders at once, use os.makedirs:
os.makedirs("path/to/something")
Then all that structure of three folders will be created.
Tutorialspoint has a short tutorial about os.mkdir.
You can use with statement like this:
with open('some_file_100.txt', 'a') as f:
pass
The above will just create an empty file, if you want to write something to the created file, you can try:
with open('some_file_100.txt', 'a') as f:
f.write('some text')
When you use with statement you do not need to close your files explicitly because they are closed autmatically at the end of the block.

Errno13, Permission denied when trying to read file

I have created a small python script. With that I am trying to read a txt file but my access is denied resolving to an no.13 error, here is my code:
import time
import os
destPath = 'C:\Users\PC\Desktop\New folder(13)'
for root, dirs, files in os.walk(destPath):
f=open(destPath, 'r')
.....
Based on the name, I'm guessing that destPath is a directory, not a file. You can do a os.walk or a os.listdir on the directory, but you can't open it for reading. You can only call open on a file.
Maybe you meant to call open on one or more of the items from files
1:
I take it you are trying to access a file to get what's inside but don't want to use a direct path and instead want a variable to denote the path. This is why you did the destPath I'm assuming.
From what I've experienced the issue is that you are skipping a simple step. What you have to do is INPUT the location then use os.CHDIR to go to that location. and finally you can use your 'open()'.
From there you can either use open('[direct path]','r') or destPath2 = 'something' then open(destPath2, 'r').
To summarize: You want to get the path then NAVIGATE to the path, then get the 'filename' (can be done sooner or not at all if using a direct path for this), then open the file.
2: You can also try adding an "r" in front of your path. r'[path]' for the raw line in case python is using the "\" for something else.
3: Try deleting the "c:/" and switching the / to \ or vice versa.
That's all I got, hope one of them helps! :-)
I got this issue when trying to create a file in the path -C:/Users/anshu/Documents/Python_files/Test_files . I discovered python couldn't really access the directory that was under the user's name.
So, I tried creating the file under the directory - C:/Users/anshu/Desktop .
I was able to create files in this directory through python without any issue.

Reading gzipped data in Python

I have a *.tar.gz compressed file that I would like to read in with Python 2.7. The file contains multiple h5 formatted files as well as a few text files. I'm a novice with Python. Here is the code I'm trying to adapt:
`subset_path='c:\data\grant\files'
f=gzip.open(filename,'subset_full.tar.gz')
subset_data_path=os.path.join(subset_path,'f')
The first statement identifies the path to the folder with the data. The second statement tells Python to open a specific compressed file and the third statement (hopefully) executes a join of the prior two statements.
Several lines below this code I get an error when Python tries to use the 'subset_data_path' assignment.
What's going on?
The gzip module will only open a single file that has been compressed, i.e. my_file.gz. You have a tar archive of multiple files that are also compressed. This needs to be both untarred and uncompressed.
Try using the tarfile module instead, see https://docs.python.org/2/library/tarfile.html#examples
edit: To add a bit more information on what has happened, you have successfully opened the zipped tarball into a gzip file object, which will work almost the same as a standard file object. For instance you could call f.readlines() as if f was a normal file object and it would return the uncompressed lines.
However, this did not actually unpack the archive into new files in the filesystem. You did not create a subdirectory 'c:\data\grant\files\f', and so when you try to use the path subset_data_path you are looking for a directory that does not exist.
The following ought to work:
import tarfile
subset_path='c:\data\grant\files'
tar = tarfile.open("subset_full.tar.gz")
tar.extractall(subset_path)
subset_data_path=os.path.join(subset_path,'subset_full')

Categories