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?