How to delete characters from a string within a Python array

Asked

Viewed 512 times

2

I’m starting in python and decided to mess with files .txt. I did the following procedure to insert values into an array, and from it insert each value into a row of a file filename.txt.

def insertFile():
    vet = []
    for j in range(2):
        subVet = []
        for i in range(2):
            subVet.append(raw_input())
        vet.append(subVet)

    file = open("filename.txt", "w")
    file.close()

    file = open("filename.txt", "w")
    for j in range(2):
        for i in range(2):
            file.write(vet[i][j]+'\n')
    file.close()

    file = open("filename.txt", "r")
    print(file.read())
    file.close()

The content of filename.txt is as follows

1
2
3
4

So I save in an external document the values I used and can access them later. For this, I did another procedure that should read the file and re-insert the content in the same size matrix as the previous procedure:

def readFile():
    vet = []
    file = open("filename.txt", "r")
    for j in range(2):
        subVet = []
        for i in range(2):
            subVet.append(file.readline())
        vet.append(subVet)
    file.close()

    print vet

I have two problems here. The first is that the content of the matrix is:

[['1\n', '2\n'], ['3\n', '4']]

Note that the last element does not have \n. The idea is to just stay:

[['1', '2'], ['3', '4']]

Without the \n. I tried to remove some ways with split, replace but was unsuccessful.

The second would be to make them whole, but I believe if I can get the \n just use int().

Does anyone know how to proceed?

1 answer

2


To remove the character \n of the line, just you use the method strip:

subVet.append(file.readline().strip())

The method strip will return a string by removing blanks and \n both at the beginning and at the end of the string original, thus the line "1\n" will return "1". If you want to convert to whole, just use the function int:

subVet.append(int(file.readline().strip()))

Other than that, your code can be improved.

From what I understand of the code, you are reading a 2x2 matrix of the user and want to save each value in a row in a file. To open the file, I recommend you use the context manager with the with, so no need to worry about closing the file. Incidentally, you open the file and then close it in function insertFile. This didn’t make much sense and if it’s just to clean up the current contents of the file, it’s unnecessary. Open the file in mode w already does it. In my view, its function insertFile could turn out like this:

from itertools import chain

def insert_file(filename):
    with open(filename, "w") as file:
        matrix = []
        for i in range(2):
            row = []
            for j in range(2):
                row.append(raw_input())
            matrix.append(row)
        file.write("\n".join(chain(*matrix)))

The function chain will make a matrix of the form [["1", "2"], ["3", "4"]] turn ["1", "2", "3", "4"]. With "\n".join() we created a string with the values of the previous list separated by a \n, getting: "1\n2\n3\n4\n", so when we write to the file, each value will be in a row.

Already in the reading I believe that it has not much to do different than it has already done:

def read_file(filename):
    with open(filename, "r") as file:
        matrix = []
        for i in range(2):
            row = []
            for j in range(2):
                row.append(int(file.readline().strip()))
            matrix.append(row)
    return matrix

See working on Repl.it | Ideone

  • Thank you very much! :)

  • @Emanoelfraguas has some improvements that can be made to the code. I am working on the answer...

  • All right, from what I’ve seen on other sites has a more 'clean' way of doing the codes in python. As I came from Pascal I end up having some old habits. But I believe that with practice and searches I end up optimizing more. These codes are in my Github (I learned to use recently haha), including this dai.

  • @Emanoelfraguas made the changes. See if it’s understandable.

  • It really got better. I’m going to find out more about with/as and chain. Thanks again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.