Charlie-5
Charlie-5

Reputation: 43

Python 3.6: Looping through files in os.listdir() and writing some of them to a text document

I'm trying to loop through some files and write the file names of the .txt ones to another .txt

the piece of code stops after finding and writing the name of one file.

how would I get it to write the names of the rest?

import os

os.chdir('/users/user/desktop/directory/sub_directory')

for f in os.listdir():
    file_name, file_ext = os.path.splitext(f)
    if file_ext == '.txt':
        with open('file_test.txt', 'r+') as ft:
            ft.write(file_name)

Upvotes: 2

Views: 8978

Answers (3)

SACHIN SHAKYA
SACHIN SHAKYA

Reputation: 1

If you are on windows then you have to use \\\ while specifying path of the directory. and write to file in append mode. See image

Upvotes: 0

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Opening the file only once before the loop would be much more efficient. And better to pass your path to os.listdir() than to change directory:

import os

with open('file_test.txt', 'w') as ft:
    for f in os.listdir('/users/user/desktop/directory/sub_directory'):
        file_name, file_ext = os.path.splitext(f)
        if file_ext == '.txt':
            ft.write(file_name)

And finally, if you want all ".txt" file in a directory, glob.glob is your friend...

Upvotes: 1

Crash Overflow
Crash Overflow

Reputation: 82

You need to open the destination file in "append" mode

import os

os.chdir('/users/user/desktop/directory/sub_directory')

for f in os.listdir():
    file_name, file_ext = os.path.splitext(f)
    if file_ext == '.txt':
        with open('file_test.txt', 'a+') as ft:
            ft.write(file_name)

Just put "a+" as second argument of your open function (where "a" stays for "append" and "+" for "create if not exists"). I suggest you to add a separator (like a "\n") in your write function to have more readable results

Upvotes: 1

Related Questions