Python Forum
Issue w/ "With Open" - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Issue w/ "With Open" (/thread-39032.html)



Issue w/ "With Open" - vman44 - Dec-23-2022

Hi,

I'm using code, similar to this:

        with open(dbfileA, 'a') as writer:
            for in_val in userinputs:
                writer.write("%s" % (in_val))
                writer.write("%s" % (comma_t1))
            writer.write("%s" % ('\n'))
I have 2 questions:
  1. Do I have to keep using the %s format, or is there an easier way?
    I've seen websites where they say to just use writer.write(in_val), but that doesn't work.
  2. How do I close the file after the with & for loop ends?
    Does it automatically close? Multiple users will be running this app, & I would like
    for the file to close after the program has finished writing the user input to the file.

Thanks.


RE: Issue w/ "With Open" - praveencqr - Dec-23-2022

You can just write the lines directly into the file. The file will close automatically. Multiple functions could simultaneously open and close the file, but the writing orders wouldn't be as you would expect.


for item in full_list:
    with open('file.txt' 'a', encoding='utf-8', errors='ignore') as file:
        file.write(str(item) + '\n')



RE: Issue w/ "With Open" - perfringo - Dec-23-2022

@praveencqr: there is no need to open and close file on every write to file. In that sense @vman44 code is correct - open the file and write rows.

Alternatively one can use print for writing into file and advantage of this is that you don't need to worry about newline:

with open(dbfileA, 'a') as writer:
    for in_val in userinputs:
        print(in_val, file=writer)



RE: Issue w/ "With Open" - snippsat - Dec-23-2022

(Dec-23-2022, 06:59 AM)vman44 Wrote: Do I have to keep using the %s format, or is there an easier way?
%s is the old way to do string formatting,should not use it anymore.
The way now is to use f-Strings
Post a working code example now have guess,usually so is userinputs a string that have to be split it up.
If want to add comma can be done lke this.
userinputs = 'hello world 123'
userinputs = userinputs.split()
with open('file1.txt', 'a') as writer:
    writer.write(f"{','.join(userinputs)}\n")
If i run two times.
Output:
hello,world,123 hello,world,123