-1

I am doing files with dictionaries and csv library and stuff, then I decided to work without csv library and the files worked great but when I decided to add for loops they don't work the first file 'some_file_1.txt' was created but empty and the second file 'some_file_2.txt' was just not even created... the error only happens with the for loop...

object_file_handler = open('some_file_1.txt', 'w') 
for c in range(1,10+1):
  object_file_handler.write('hello world ! ',c,' \n ') 
object_file_handler.close() 




with open('some_file_2.txt', 'w') as object_file_handler: 
  for c in range(1,20+1):
    object_file_handler.write('I LOVE MUSIC !\n',c) 

3 Answers3

1

The solution was this, apparently you can not use comas on files you need the plus symbol .... but if you want to elaborate further I would love that!

object_file_handler = open('some_file_1.txt', 'w') 
for c in range(1,10+1):
  object_file_handler.write('hello world ! '+str(c)+' \n ') 
object_file_handler.close() 




with open('some_file_2.txt', 'w') as object_file_handler: 
  for c in range(1,20+1):
    object_file_handler.write('I LOVE MUSIC ! '+str(c)+' \n ') 
1

TypeError: write() takes exactly one argument (3 given) is presumably the error you're running into.

The error is occuring because it's seeing the 'hello world!', c and \n as three separate arguments due to the commas. You can use string concatenation or f-strings.

Try running your code with this:

object_file_handler = open('some_file_1.txt', 'w') 
for c in range(1,10+1):
  object_file_handler.write(f'hello world ! {c} \n ') 
object_file_handler.close() 




with open('some_file_2.txt', 'w') as object_file_handler: 
  for c in range(1,20+1):
    object_file_handler.write(f'I LOVE MUSIC !\n {c}') 
Diggy.
  • 6,744
  • 3
  • 19
  • 38
1

Also this works perfectly;

object_file_handler = open('some_file_1.txt', 'w') 
for c in range(1,10+1):
  object_file_handler.write(f'hello world  {c}!  \n') 
object_file_handler.close() 




with open('some_file_2.txt', 'w') as object_file_handler: 
  for c in range(1,20+1):
    object_file_handler.write(f'I LOVE MUSIC  {c}!  \n')