-3

How to write to text file python 3?

I want to read each line and write to outputDoc1.txt for line1 , outputDoc2.txt for line1, outputDoc3.txt for line1

line1 = "Alright, I think I understand. Thank you again"
line2 = " just had to use join to separate the data"
line3 = " whether that's desirable or not I suppose is down to the OP"
path = "C:\\Users\\subashini.u\\Desktop\\"

l=["line1","line2","line3"]
count = 0
for txt_file in l:
    count += 1
    for x in range(count):
        with open(path + "outputDoc%s.txt" % x) as output_file:
            output_file.write(txt_file)
            #shutil.copyfileobj(file_response.raw, output_file)
            output_file.close()
pycoderr
  • 57
  • 5
  • 1
    Why are you closing the file a) after you write a single line, and b) at all? The `with` expression will close the file for you. – Makoto Jun 19 '19 at 04:19
  • Is there a reason where you need to write one line at a time to each file? Because right now you'll do line1, line1, line1, line2, etc. If that's not required then I would recommend writing all of the lines at once to each file so you're not reopening the files every time a new line needs to be written. – Zach Woods Jun 19 '19 at 04:26
  • What is wrong with the current code, what is the issue? – AMC Nov 03 '20 at 02:08

3 Answers3

1
line1 = "Alright, I think I understand. Thank you again"
line2 = " just had to use join to separate the data"
line3 = " whether that's desirable or not I suppose is down to the OP"
path = "D://foldername/"

ls=[line1,line2,line3]

for i, l in enumerate(ls, start=1):
    with open(path + "outputDoc%s.txt" % i, 'w') as output_file:
        output_file.write(l)
nag
  • 749
  • 4
  • 9
0

you're missing the write attribute in file open and referring to string and not line elements:

just change

loop to:

l=[line1,line2,line3]
count = 0
for txt_file in l:
    print(txt_file)
    count += 1
    with open(path + "outputDoc%s.txt" % count, 'w') as output_file:
        output_file.write(txt_file + '\n')

it writes:

line1 in <path>/outputDoc1.txt

line2 in <path>/outputDoc2.txt

etc

cccnrc
  • 1,195
  • 11
  • 27
0

First of all, you currently don't write the lines you want.

Change

l=["line1","line2","line3"]

to

l = [line1, line2, line3]

Then, to make things a bit easier, you could do something like this:

for i, line in enumerate(l, start=1):
    ...

To open the file and write something, you need to open it with the correct mode -> 'write'. The default mode with open() is read, therefore you currently can't write to the file.

with open('file', 'w') as f:
    ...
    # no f.close() needed here
wfehr
  • 2,185
  • 10
  • 21