I am reading a file in python and i need to add every line to a list. The problem is that every line is a list containing string and integers. This is the file i am reading:
file
this is the output of reading the file and putting it on the new list.
output
as you can see it is storing me the lines as a string but it need to be like this:
correct output
CODE:
def build_sets(f):
lista_valores = []
with open(f, 'r') as f:
for line in f:
lista_valores += line.strip().split('\n')
print(lista_valores)
#pass
Try this in your for loop:
lista_valores = line.strip('][').split(', ')
Also please only use english words to define your variables, it's one of the main rules of variable naming conventions.
Use ast.literal_eval with which you can safely evaluate an expression node or a string containing a Python literal or container display. Hence it will evluate your string as a proper list.
import ast
def build_sets(f):
lista_valores = []
with open(f, "r") as f:
a = f.read().splitlines()
for item in a:
lista_valores.append(ast.literal_eval(item))
print(lista_valores)
Output:
[[1, 'a', 'b'], [2, 'b', 'c']]
thank you guys, i figured it out this way:
lista_valores = []
with open(f, 'r') as f:
for line in f:
linha = line[0:len(line)-1].strip("[]").split(',')
lista_valores.append(linha)
for i in range(len(lista_valores)): # convert to int
for j in range(len(lista_valores[i])):
if lista_valores[i][j].isdigit():
lista_valores[i][j] = int(lista_valores[i][j])
I have this data in my sample.txt file:
A2B3,32:45:63
A4N6,17:72:35
S2R3,13:14:99
What I want to do is to put those data in an array but I'm having problems separating those with commas.
My code goes like this:
with open('sample.txt', 'r') as f:
for line in f:
x = f.read().splitlines()
print(x)
And the output goes like this:
['A2B3,32:45:63','A4N6,17:72:35','S2R3,13:14:99']
I altered my code in different ways to separate those two variables with commas but I can't seem to make it work. Can someone help me achieve this output?
['A2B3','32:45:63','A4N6','17:72:35','S2R3','13:14:99']
use line.split(',') to seperate the line at the ",".
x = []
with open('sample.txt', 'r') as f:
for line in f:
for j in line.split(','):
x.append(j.split('\n')[0])
print(x)
Use this code, which splits the lines into a list like you have, and then splits those items at the comma.
filename = "sample.txt"
with open(filename) as file:
lines = file.read().split("\n")
output = []
for l in lines:
for j in l.split(","):
output.append(j)
print(output)
Output:
['A2B3', '32:45:63', 'A4N6', '17:72:35', 'S2R3', '13:14:99']
You probably could just do:
data = list()
with open('sample.txt', 'r') as f:
for line in f.readlines():
data.append(line)
And you should end up with list of appended lines. It's also faster on big files than just .splitlines() since .readlines() is implemented in C and doesn't load whole file in memory.
yes, it's very simple...
after separate all line, you get list look like
['A2B3,32:45:63','A4N6,17:72:35','S2R3,13:14:99']
then after again you separate that each element by comma(,) and add it into new list like
list_a = ['A2B3,32:45:63','A4N6,17:72:35','S2R3,13:14:99']
final_list = []
for i in list_a:
part_1, part_2 = i.split(',')
final_list.append(part_1)
final_list.append(part_2)
print(final_list)
And it will give your desire output like
['A2B3','32:45:63','A4N6','17:72:35','S2R3','13:14:99']
it is not a redundant way but for you very easy to understand
Thank You :)
Here you go, just iterating once over the lines:
res = []
with open('sample.txt', 'r') as f:
for line in f:
res += line.strip().split(",")
print(res)
Gives:
['A2B3', '32:45:63', 'A4N6', '17:72:35', 'S2R3', '13:14:99']
Though I wonder why you'd want to have everything in a list, I think you are missing the link between the items, maybe could be more useful to keep them in tuples like this:
res = []
with open('sample.txt', 'r') as f:
for line in f:
res.append(tuple(line.strip().split(",")))
print(res)
Gives:
[('A2B3', '32:45:63'), ('A4N6', '17:72:35'), ('S2R3', '13:14:99')]
FMPOV this result is better to go along. But nevermind, I guess, you'll find your solution from one of those poseted here.
x = [i.replace("\n","").split(',')for i in open('data.txt', 'r')]
print(x)
print(x[0][1])
I'm working on a Python project in Visual Studio. I want to process a longer text file, this is a simplified version:
David Tubb
Eduardo Cordero
Sumeeth Chandrashekar
So for reading this file I use this code:
with open("data.txt", "r") as f:
f_contents = f.read()
print(f_contents)
I want to put these items into a new array that looks like that:
['David Tubb','Eduardo Cordero','Sumeeth Chandrashekar']
Is that possible?
Yes, the following code will work for this:
output = [] # the output list
nameFile = open('data.txt', 'r')
for name in nameFile:
# get rid of new line character and add it to your list
output.append(name.rstrip('\n'))
print output
# don't forget to close the file!
nameFile.close()
result = []
with open("data.txt", "r") as f:
result = f.read().splitlines()
print(result)
Output:
['David Tubb', 'Eduardo Cordero', 'Sumeeth Chandrashekar']
The method stated by python for opening a file context is using "with open", this ensures the context will end during clean up.
python.org-pep-0343
dalist = list()
with open('data.txt', 'r') as infile:
for line in infile.readlines():
dalist.append(line)
Additonal resource for contex handeling: https://docs.python.org/3/library/contextlib.html
I need to add some text to the end of a specific line in a text file. I'm currently trying to use a method similar to this:
entryList = [5,4,3,8]
dataFile = open("file.txt","a+)
for i in dataFile:
for j in entryList:
lines[i] = lines[i].strip()+entryList[j]+" "
dataFile.write(lines[i])
I'd like to add the numbers immediately following the text.
Text file setup:
it is
earlier it was
before that it was
later it will be
You have mentioned specific line in the question and in your code you are writing for every line.
import fileinput
entryList = [5,4,3,8]
count = 0
for line in fileinput.FileInput('data.txt',inplace=1):
print line+str(entryList[count])+" "
count+=1
Reading from and then writing to the same file is not such a good idea. I suggest opening it as needed:
entryList = [5,4,3,8]
with open("file.txt", "r") as dataFile:
# You may want to add '\n' at the end of the format string
lines = ["{} {} ".format(s.strip(), i) for s,i in zip(dataFile, entryList)]
with open("file.txt", "w") as outFile:
outFile.writelines(lines)
I'm trying to read a csv file into a list. However, my code doesn't produce what it's supposed to.
data_list = []
data_file = open('table.csv', 'r')
for line in data_file:
data_list.append(line.strip().split(','))
print (data_list)
It produces this:
I couldn't code it on here so I had to attach a photo (sorry). Why does it do this? I just want a normal list of lists.
You're printing inside the for loop. data_list is a list of lists, just print it after the for loop finishes :)
data_list = []
data_file = open('table.csv', 'r')
for line in data_file:
data_list.append(line.strip().split(','))
print(data_list)