How to delete characters from a string inside a Python array

2

I'm starting in python and I've decided to fiddle with .txt files. I did the following procedure to insert values into an array, and from that insert each value into a line of a filename.txt file.

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 saved in an external document the values I used, and you can access them later. To do this, I did another procedure that should read the file and re-insert the contents in the same-sized array 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 contents of the array is:

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

Note that the last element does not have \n . The idea is that it should only be:

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

Without the \n . I tried to remove it in some ways with split, replace but I did not succeed.

The second one would be to transform them into an integer, but I think if you can remove \n just use int() .

Does anyone know how to proceed?

    
asked by anonymous 26.10.2017 / 18:38

1 answer

2

To remove the \n character from the line, simply use the strip method:

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

The strip method will return a string by removing whitespace and \n both from the beginning and the end of the original string , thus, will return% with%. If you want to convert to integer, just use the "1\n" function:

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

Otherwise, your code can be improved.

From what I understand from the code, you are reading a 2x2 user array and want to save each value in a row on a line. To open the file, I recommend using the context manager with "1" , so you do not have to worry about closing the file. Incidentally, you open the file and then close it in the int function. This did not make much sense and if it is just to clean the current contents of the file, it is unnecessary. Opening the file in with mode already does this. As I see it, its insertFile function could look 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 w function will cause an array of the insertFile form to chain . With [["1", "2"], ["3", "4"]] we create a string with the values of the previous list separated by a ["1", "2", "3", "4"] , being: "\n".join() , so when we write in the file, each value will be in a row. >

In reading, I believe that you do not have much to do other than what you have 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 at Repl.it | Ideone

    
26.10.2017 / 19:11