text file cannot be made a folder - python

test.txt cannot be made. I want to make a folder&text file when I write a directory in html's form like:
.
The code:
os.makedirs(directory, exist_ok=True)
f = open(directory, 'w')
f.write("testtesttesttest")
f.close()
I want to make 0422 folder in /Users/xxx/Downloads,and test.txt in 0422 folder.
But when I run the file and I put directory in the form, 0422 folder was made and test.txt "folder" was made in 0422 folder.
I want to make test.txt (text file) in the folders. What is the problem in the code? Directory's variable can be gotten /Users/xxx/Downloads/0422/test.txt ,so it is ok.
How should I fix this?

You need to first create the directories, then create the file:
import os
directory = '/Users/xxx/Downloads/free.txt'
os.makedirs(os.path.dirname(directory), exist_ok=True)
with open(directory, 'w') as f:
f.write('blah blah')

You need to make one addition of the open statement.
os.makedirs(directory, exist_ok=True)
f = open(directory +'/test.txt', 'w')
f.write("testtesttesttest")
f.close()
We need to mention the text.txt somewhere

Related

Open a file in python from 2 directory back

I want to read a file from 2 folders back..
with open('../../test.txt', 'r') as file:
lines = file.readlines()
file.close()
I want to read from ../../ two folders back. but not work..
How i can do that ?
Opening files in python is relative to the current working directory. This means you would have to change cd to the directory where this python file is located.
If you want a more robust solution:
To be able to run this from any directory, there is a simple trick:
import os
PATH = os.path.join(os.path.dirname(__file__), '../../test.txt')
with open(PATH, 'r') as file:
lines = file.readlines()
file.close()

Read in multiple folder and combine multiple text files contents to one file per folder - Python

I'm new to Python. I have 100's of multiple folders in the same Directory inside each folder i have multiple text files each. i want to combine all text files contents to one per folder.
Folder1
text1.txt
text2.txt
text3.txt
.
.
Folder2
text1.txt
text2.txt
text3.txt
.
.
i need output as copy all text files content in to one text1.txt + text2.txt + text3.txt ---> Folder1.txt
Folder1
text1.txt
text2.txt
text3.txt
Folder1.txt
Folder2
text1.txt
text2.txt
text3.txt
Folder2.txt
i have below code which just list out the text files.
for path,subdirs, files in os.walk('./data')
for filename in files:
if filename.endswith('.txt'):
please help me how to proceed on the task. Thank you.
Breaking down the problem we need the solution to:
Find all files in a directory
Merge contents of all the files into one file - with the same name as the name of the directory.
And then apply this solution to every sub directory in the base directory. Tested the code below.
Assumption: the subfolders have only text files and no directories
import os
# Function to merge all files in a folder
def merge_files(folder_path):
# get all files in the folder,
# assumption: folder has no directories and all text files
files = os.listdir(folder_path)
# form the file name for the new file to create
new_file_name = os.path.basename(folder_path) + '.txt'
new_file_path = os.path.join(folder_path, new_file_name)
# open new file in write mode
with open(new_file_path, 'w') as nf:
# open files to merge in read mode
for file in files:
file = os.path.join(folder_path, file)
with open(file, 'r') as f:
# read all lines of a file and write into new file
lines_in_file = f.readlines()
nf.writelines(lines_in_file)
# insert a newline after reading each file
nf.write("\n")
# Call function from the main folder with the subfolders
folders = os.listdir("./test")
for folder in folders:
if os.path.isdir(os.path.join('test', folder)):
merge_files(os.path.join('test', folder))
First you will need to get all folder names, which can be done with os.listdir(path_to_dir). Then you iterate over all of them, and for each you will need to iterate over all of its children using the same function, while concatenating contents using this: https://stackoverflow.com/a/13613375/13300960
Try writing it by yourself and update the answer with your code if you will need more help.
Edit: os.walk might not be the best solution since you know your folder structure and just two listdirs will do the job.
import os
basepath = '/path/to/directory' # maybe just '.'
for dir_name in os.listdir(basepath):
dir_path = os.path.join(basepath, dir_name)
if not os.path.isdir(dir_path):
continue
with open(os.path.join(dir_path, dir_name+'.txt') , 'w') as outfile:
for file_name in os.listdir(dir_path):
if not file_name.endswith('.txt'):
continue
file_path = os.path.join(dir_path, file_name)
with open(file_path) as infile:
for line in infile:
outfile.write(line)
This is not the best code, but it should get the job done and it is the shortest.

how to include folders in python code

Let's say two folders. One -X and one more-Y inside X.Now lets say I've set my working path to folder X inside ATOM IDE and now if I want use the folder Y in my code how do I do it?
for example while writing below code I'm inside folder X so
import glob2
import datetime
filenames = glob2.glob('*.txt')
#How do I list files of folder Y only???
with open(datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f")+".txt", 'w') as file:
#How do I create file inside folder Y only
for item in filenames:
with open(item,"r") as f:
content = f.read()
file.write(content)
file.write("\n")
You can use below code to switching around different directory
Path='path to y'
currentDir = os.getcwd()
os.chdir(Path)
#do your job here
#now come back to previous directory
os.chdir(currentDir)
Let's take your directory structure :
x/
some_script.py
y/
Now what you're looking for is to create a file inside y by writing some code in some_script.py
This is how you do it :
fh = open('y/a.txt', 'w')
fh.write("Yayy")
fh.close()

How to loop to directory and json the output to txt file?

So I want to loop through a directory of text files (.txt) and print the output(names of all txt files) in a separate file using json.dump?
So far i only have:
data = #name of txt files in directory
with open('file.txt','w') as ofile:
json.dump(data,ofile)
You can write this code, assuming your directory is the current directory (.)
import os
import json
directory_path = '.' #Assuming your directory path is the one your script lives in.
txt_filenames = [fname for fname in os.listdir(directory_path) if fname.endswith('.txt')]
with open('file.txt', 'w') as ofile:
ofile.write(json.dumps({
'filenames': txt_filenames
}))
So, your output file (in this case file.txt) will look like this:
"filenames": ["a.txt", "b.txt", "c.txt"]}
Hope it helps,

Opening a file in a folder in Python?

I want to open a file to write to.
with open(oname.text , 'w') as f:
and now I want to write the files in a folder "Playlist"
I know that I have to use os.path But I do not know how to use it
ty all
path = os.path.join('Playlist', oname.text)
with open(path, 'w') as f:
...
If you're not sure if the 'Playlist' subdir of the current directory already exists, prefix that with:
if not os.path.isdir('Playlist'):
if os.path.exists('Playlist'):
raise RuntimeError('Playlist exists and is a file, now what?!')
os.mkdir('Playlist')
This raises an exception if 'Playlist' does exist but as a file, not a directory -- handle this anomalous case as you wish, but unless you remove or rename the file, you're not going to be able to have it as a directory as well!
Use os.makedirs instead of os.mkdir if the path you desire has multiple levels of directories, e.g Play/List/Whatever (you could use it anyway just in case).
You could change the current working directory using os.chdir function.
os.chdir('Playlist')
with open(oname.text , 'w') as f:
...
Use with statement and os.path.join method
dir_path = "/home/Playlist"
file_path = os.path.join('dir_path, "oname.txt")
content = """ Some content..."""
with open(file_path, 'wb') as fp:
fp.write(content)
OR
fp = open(file_path, "wb"):
fp.write(content)
fp.close()

Categories