0

Question:

This is a small part in a bigger project. I'd like to believe I'm good at understanding delimiters and CSVs but I don't know what to do or what to ask.

Dumb question, how can I isolate the strings from this list and print them?

(0, 'img_10.jpg')
(1, 'img_8.mp4')
(2, 'img_31.mp4')
(3, 'img_30.mp4')
(4, 'img_9.mp4')
(5, 'img_12.jpg')
(6, 'img_20.mp4')
(7, '.DS_Store')
(8, 'img_21.mp4')
(9, 'img_35.mp4')

Desired output:

'img_10.jpg'
'img_8.mp4'
'img_31.mp4'
'img_30.mp4'
'img_9.mp4'
'img_12.jpg'
'img_20.mp4'
'.DS_Store'
'img_21.mp4'
'img_35.mp4'

My script below:

import glob, os
import sys
import csv

folder_path = "path"
list = os.listdir(folder_path)

with open("files.txt", "w", newline='\n', encoding='utf-8') as csvfile:
    i = 0
    for file in enumerate(list):
        csvfile.write(str(file) + "\n")
        print(file)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
404sigh
  • 9
  • 1

3 Answers3

1

Don't enummerate use list iterator When you enumerate the list it will give index and the element as tuple that's why you got (i,element) tuple. If you don't need indexes then you can only iterate the list elements.

Using list as a varaible name is not a good practice because it is a python keyword

folder_path = "path"
list_files = os.listdir(folder_path)

with open("files.txt", "w", newline='\n', encoding='utf-8') as csvfile:
    i = 0
    for file in list_files:
        csvfile.write(str(file) + "\n")
        print(file)
Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45
0

Since you are enumerating, you are saving also the index on your file variable, making it a tuple. file[1] should do the job on your case. If you really need the enumerator, I suggest to separate it on another variable.

Yoshi
  • 172
  • 7
0

Because you are using enumerate you are looping through tuples that includes a index for each element you have in the list.. u better remove it and your code should work fine:

import glob, os
import sys
import csv

folder_path = "path"
list_ = os.listdir(folder_path)

with open("files.txt", "w", newline='\n', encoding='utf-8') as csvfile:
        i = 0
        for file in list_:
            csvfile.write(str(file) + "\n")
        print(file)
adir abargil
  • 5,495
  • 3
  • 19
  • 29