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?
Thank you very much! :)
– Manolloz
@Emanoelfraguas has some improvements that can be made to the code. I am working on the answer...
– Woss
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.
– Manolloz
@Emanoelfraguas made the changes. See if it’s understandable.
– Woss
It really got better. I’m going to find out more about
with/as
andchain
. Thanks again.– Manolloz