Home > Enterprise >  python doesn't append each line but skips some
python doesn't append each line but skips some

Time:04-01

I have a complete_list_of_records which has a length of 550

this list would look something like this:

  1. Apples

  2. Pears

  3. Bananas

The issue is that when i use:

 with open("recordedlines.txt", "a") as recorded_lines:
      for i in complete_list_of_records:
            recorded_lines.write(i)

the outcome of the file is 393 long and the structure someplaces looks like so

  1. Apples

  2. PearsBananas

  3. Pineapples

I have tried with "w" instead of "a" append and manually inserted "\n" for each item in the list but this just creates blank spaces on every second row and still som rows have the same issue with dual lines in one.

Anyone who has encountered something similar?

CodePudding user response:

You could simply strip all whitespaces off in any case and then insert a newline per hand like so:

with open("recordedlines.txt", "a") as recorded_lines:
    for i in complete_list_of_records:
        recorded_lines.write(i.strip()   "\n")

CodePudding user response:

you need to use

file.writelines(listOfRecords)

but the list values must have '\n'

f = open("demofile3.txt", "a")
li = ["See you soon!", "Over and out."]
li = [i '\n' for i in li]
f.writelines(li)
f.close()

#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())

output will be

See you soon!
Over and out.

you can also use for loop with write() having '\n' at each iteration

CodePudding user response:

[Soln][1]

complete_list_of_records =['1.Apples','2.Pears','3.Bananas','4.Pineapples']

with open("recordedlines.txt", "w") as recorded_lines:
      for i in complete_list_of_records:
            recorded_lines.write(i "\n")

I think it should work. Make sure that, you write as a string.

  • Related