Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add a new line after each new file name in python

I have a short Python script that opens a directory and puts all of the file names into a .txt file. I have tried a few ways to add a new line after each file name but cannot do it. I also want to convert the entire string to uppercase.

Here is what I have:

import os

#Path where the photos are stored
path1 = r"V:\DATABASES\0 Suspension\Suspensia Pictures"

#Variable to list all the files in the dorectory
file_dir = os.listdir(path1)

#Opens a new text file called Pics
newfile = open('Pics.txt','w')

#Writes lines in the file as a string
newfile.write(str(file_dir))

#Prints out all the file names
#print(file_dir)ode here

What I was thinking for the new line was to add print('\n') after the newfile.write(str(file_dir)) line. However, that did not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As for the uppercase I am not sure where to put the .upper().

Thanks for the help

>Solution :

os.listdir() gives you a list of strings, so converting its output would give you a string that looks like a list of strings.

Do this instead:

#Writes lines in the file as a string
newfile.write('\n'.join(file_name.upper() for file_name in file_dir))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading