简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM