1

Here, I want to write the word_count in each loop line by line to the file. However, they are written all back to back.

import os
import string
def remove_punctuation(value):
    result = ""
    for c in value:
        # If char is not punctuation, add it to the result.
        if c not in string.punctuation and c != '،' and c != '؟' and c !   = '؛' and c != '«' and c != '»':
            result += c
    return result
def all_words(file_path):
    with open(file_path, 'r', encoding = "utf-8") as f:
        p = f.read()
        p = remove_punctuation(p)
        words = p.split()
        word_count = len(words)
        return str(word_count)
myfile = open('D:/t.txt', 'w')
for root, dirs, files in os.walk("C:/ZebRa", topdown= False):
    for filename in files:
        file_path = os.path.join(root, filename)
        f = all_words(file_path)
        myfile.write(f)
        break
myfile.close()

I have also tried to add newline, but instead, it writes nothing.

myfile.write(f'\n')
7
  • Try myfile.write((line+'\n' for line in f)). Commented Mar 12, 2019 at 21:38
  • TypeError: write() argument must be str, not generator Commented Mar 12, 2019 at 21:39
  • 1
    OK, use myfile.write([line+'\n' for line in f]) instead. Commented Mar 12, 2019 at 21:41
  • TypeError: write() argument must be str, not list Commented Mar 12, 2019 at 21:42
  • One more attempt: myfile.write('\n'.join(f) + '\n') Commented Mar 12, 2019 at 21:44

3 Answers 3

3

Change this line:

return str(word_count)

to

return str(word_count) + '\n'

If you're using python 3.6+, you could also try:

return f'{word_count}\n'
Sign up to request clarification or add additional context in comments.

Comments

1

You can write a newline character at the end of each iteration:

for root, dirs, files in os.walk("C:/ZebRa", topdown= False):
    for filename in files:
        file_path = os.path.join(root, filename)
        f = all_words(file_path)
        myfile.write(f)
        break
    myfile.write('\n')

Comments

1

When you us file.write() try using this instead:

myfile.write(f+"\n")

This will add a new line after every iteration

For your code to work, however, you need to iterate in a for loop, like this:

for string in f:
    file.write(string+"\n")

I hope this helps

1 Comment

AttributeError: 'str' object has no attribute 'punctuation'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.