0

I have a very basic question in python. I want to split the items in the following list and print it in a text file.

import pandas as pd
s = ['"9-6": 1', ' "15-4": 1', ' "12-3": 1', ' "8-4": 1', ' "8-5": 1', ' "8-1": 1']
print type(s)
for i in s:
     j = i.split(',')
     with open("out.txt","w") as text_file:
             text_file.write("{}".format(j))

However, my code only prints the last value. Clearly, it is not taking the last lines inside the for loop block. Can anyone point where am I going wrong? Thanks!

1
  • I don't understand why you do j = i.split(','), you're iterating through each string in your array and then splitting each string into substrings separated by commas, but there are no commas in any of the strings. Commented Nov 11, 2016 at 5:12

3 Answers 3

1

You are not appending the values. You are re-writing every time. Try like this:

with open("out.txt","a+") as text_file:

Here, I replaced "w" by "a+".

Full code:

import pandas as pd
s = ['"9-6": 1', ' "15-4": 1', ' "12-3": 1', ' "8-4": 1', ' "8-5": 1', ' "8-1": 1']
print type(s)
for i in s:
    j = i.split(',')
    with open("out.txt","a+") as text_file:
        text_file.write("{}".format(j))
Sign up to request clarification or add additional context in comments.

Comments

0

Every time that you open out.txt with the 'w' option, it is erasing that file completely before you even write anything. You should put the with statement before the start of the for loop, so that the file is only opened once.

Comments

0

One every iteration of your for loop, your truncating your files contents ie. "Emptying the file". This is because when using the open mode w Python implicitly truncates the file since you already created on the previous iteration. This behavior is documented in Python 2.7:

[..]'w' [is] for writing [to files] (truncating the file if it already exists)[..]

Use the option a+ instead, which appends to a file. The Python 2.7 documention also notes this:

[..] [use] 'a' for appending [..]

Which means that this:

...open('out.txt' 'w')...

should be:

...open('out.txt', 'a')...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.