0

I wanted to loop through some files and put the content of those files into a new list but when I run the code, the result shows "None'.

import os
import glob

folder = os.path.join("R:", os.sep, "Files")
list = []

def notes():

    for file in glob.glob(folder):
        if file.endswith('.docx'):
            with open(file,'r+') as f:
                content = f.read()
                for text in content:
                    new_list = list.append(text)
                return new_list

print(notes())
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • 3
    `list.append(text)` returns `None`. It just simply appends the `list` with `text` value and returns nothing. – Underoos Aug 11 '19 at 09:09
  • i tried it but it still shows None. i think something else is wrong with my code? –  Aug 11 '19 at 09:15
  • You are finally returning `new_list` variable whose value is actually `None`. – Underoos Aug 11 '19 at 09:15
  • i change it to return list but it still shows none –  Aug 11 '19 at 09:17
  • change `new_list = list.append(text)` into `new_list.append(text)`, and move the return statement to the first indent. Also rename the variable name `list` to `new_list` since `list` is a python internal – Joost Döbken Aug 11 '19 at 09:21
  • Now it shows an empty list ([]) –  Aug 11 '19 at 09:23
  • You changed your question by editing the code it contains. Please never do that on SO: it makes all the comments and potential answers to the original version irrelevant. If you now have a different problem and you can't find an answer after researching it, either add the new info in the comments or ask a different question. (I rollback your last edit to go back to the original version of the question) – Thierry Lathuille Aug 11 '19 at 09:53
  • Thank you. I don't know this as I am new to this site. –  Aug 11 '19 at 10:21
  • What's wrong with my code? –  Aug 11 '19 at 10:22
  • I removed new_list and moved the return statement to the first indentation but the result now shows an empty list ([]). –  Aug 11 '19 at 10:24
  • As someone stated, first you should remove the `list=[]` line. Then I would recommend declaring the variable you are returning in function definition. Add `new_list = []` in first indent after `def` and change `new_list = list.append(text)` to `new_list.append(text)`. Also do `glob.glob(folder + r'\*')`, as glob matches by pattern. You could even skip the `file.endswith('.docx')` and do `glob.glob(folder + r'\*.docx')`. You have already moved the return to first indent, so this should work. – TheDecks Aug 11 '19 at 10:59

0 Answers0