0

I've written a small script to append a character to the end of each line of a text file, "," in my case.

This will be shared with my team, so rather than have them update the script itself I thought it would be easier to simply define a variable at the start they can change.

However, it takes 'char' as a literal string and appends 'char' rather than ',' in the test file. If I swap char\n back to ,\n it appends a comma correctly.

How do I fix this?

file = 'test.txt' # file to append text to, keep the '' 
char = ','

newf=""
with open(file,'r') as f:
    for line in f:
        newf+=line.strip()+'char\n'
    f.close()
with open(file,'w') as f:
    f.write(newf)
    f.close()
mak47
  • 303
  • 2
  • 14
  • 2
    Also note that `f` is closed after you leaved the indented `with` block so no need to call `f.close()`. – Kraigolas Aug 08 '22 at 14:56
  • 2
    Check f-strings formatting. https://datagy.io/python-f-strings/ In your case, it can be something like `newf += f'{line.strip()}{char}\n'` – alec_djinn Aug 08 '22 at 14:57
  • 1
    You might also improve your code by using something like [argparse](https://docs.python.org/3/library/argparse.html), which would allow users to provide `char` and `file` from the commandline without having to edit the script at all. – Kraigolas Aug 08 '22 at 14:58
  • 1
    I cant answer anymore since this was closed. However if youre just updating a file Id encourage you to do it in place instead of saving everything to a string and then writing it. Heres some code using in_place which can be installed with pip install in_place: import in_place charToAdd = ',' with in_place.InPlace('data.txt') as file: for line in file: file.write(line.strip() + charToAdd + '\n') – mradey Aug 08 '22 at 15:10

2 Answers2

1

You were passing variable name as string instead of passing the variable. Try this:

file = 'test.txt' # file to append text to, keep the ''
char = ','

newf=""
with open(file,'r') as f:
  for line in f:
      newf+=line.strip()+char+'\n'
  f.close()
with open(file,'w') as f:
  f.write(newf)
  f.close()
0

As char is a variable you have to place it outside the quotation marks, otherwise it is interpreted as a string.

file = 'test.txt' # file to append text to, keep the '' 
char = ','

newf=""
with open(file,'r') as f:
    for line in f:
        newf+=line.strip()+ char + '\n'
with open(file,'w') as f:
    f.write(newf)
    
LeBavarois
  • 938
  • 2
  • 11
  • 24