2

I have a very basic problem.I have wrote a code which open a .txt file which contain a numbers 1 2 3 4 5 6 7 8 9.Then it square all of it and write to other file. Right now I want to add to this code procedure which split all of this numbers in rows and rewrite,like this:

1 4 9
16 25 36
49 64 81

My code already:

n=[]
dane = open("num.txt", "r")

for i in dane:
  i = i.replace('\n','')
  for j in i.split(' '):
        j = int(j)
        j = j**2
        n.append(j)

nowy = open("newnum.txt","w")
nowy.write(str(n))
nowy.close()
2
  • 1
    So what is the problem with the code? Commented Mar 29, 2015 at 10:38
  • how your actual input looks like? Commented Mar 29, 2015 at 10:41

4 Answers 4

2

The code you have written works fine expect for the writing part. For which you need to change the last three lines of code as

nowy = open("newnum.txt","w")
for i in range(0,len(n),3):
    nowy.write("{} {} {}\n".format(n[i],n[i+1],n[i+2]))
nowy.close()

The for loop can be explained as,

  • loop through the list n that you have generated 3 at a time by using the third argument to the range function which is called step.
  • write out the values three at a time into the file, terminated by the newline character

The output after changing the lines of code is as expected

1 4 9
16 25 36
49 64 81

Ref:

Sign up to request clarification or add additional context in comments.

1 Comment

@wiedzminYo All the best :)
1

As a complement to @Bhargav's answer, according to the doc "[a] possible idiom for clustering a data series into n-length groups [is] using zip(*[iter(s)]*n)"

You can use the star to unpack a list/tuple as arguments to format function call too.

All this will lead to a more Pythonic (or, rather crypto-Pythonic ?) version of the writing part:

with open("newnum.txt","w") as nowy:
    for sublist in zip(*[iter(n)]*3):
        nowy.write("{} {} {}\n".format(*sublist))

Please note the use of a context manager (with statement) to ensure proper closing of the file in all cases when exiting from the block. As other changes would be subject to discussion, that later is a must -- and you should definitively take the habit of using it
(BTW, have you noticed you never closed the dane file? A simple mistake that would have been avoided by the use of a context manager to manage that resource...)

Comments

0

You can try this:

strNew = ''
dane = open("num.txt", "r")
row = 0
for i in dane:
  i = i.replace('\n','')
  for j in i.split(' '):
    row += 1
    j = int(j)
    j = j**2
    if (row % 3) == 0:
        strNew += str(j)+'\n'
    else:
        strNew += str(j) + ' ' # it can be ' ' or '\t'

nowy = open("newnum.txt","w")
nowy.write(strNew)
nowy.close()

The result is:

1 4 9
16 25 36
49 64 81

Comments

0
n=[]
dane = open("num.txt", "r")

for i in dane:
  i = i.replace('\n','')
  for j in i.split(' '):
        j = int(j)
        j = j**2
        # new code added
        # why str(j)? Because array in Python can only have one type of element such as string, int, etc. as opposed to tuple that can have multiple type in itself. I appended string because I wanna append \n at the end of each step(in outer loop I mean)
        n.append(str(j))

  # new code added
  n.append("\n")

nowy = open("newnum.txt","w")
nowy.write(str(n))
nowy.close()

1 Comment

"array in Python can only have one type of element". n is a Python list; Python doesn't have a native array type (although a Python list is implemented in CPython as an array of pointers). The elements of a Python list do not have to be of the same type. However, it's generally considered good programing style to avoid mixing types in a list (apart from special values like None), but that's a guideline, not a hard & fast rule.

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.