Why does my code produce this output (Python)? - python

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)

Related

I need to load data to my python3 program from a file

I need to load data to my python program from a file. Could you tell me what is the easiest way?
the file is user_id.txt and content is :
['1668938807', '8646077542', '2926881681', '634754486']
also what I tried but did not work is:
with open('user_id.txt', 'r') as f:
data = f.readlines()
lines = []
for line in data:
content = line.split(',')
for el in content:
new_el = el.strip('\'')
print(new_el)
Below (using the fact that the file content can be directly loaded into a list using ast)
import ast
with open('user_id.txt') as f:
lst = ast.literal_eval(f.read())
print(lst)
output
['1668938807', '8646077542', '2926881681', '634754486']
If you want to load numbers to array you can try this:
numbers = []
with open("user_id.txt","r") as f:
data = f.readlines()
for line in data:
stripped = ex[1:-1] #stripped bracelets
numbers.append([ int(''.join(filter(str.isdigit, num))) for num in stripped.split(",") ] )
Anyway you should consider using json
Hope i answered your question

Extracting data from a .txt file

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])

Putting items into array

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

How can I properly read in this text data to a list?

I have some data in a .txt file structured as follows:
Soup Tomato
Beans Kidney
.
.
.
I read in the data with
combo=open("combo.txt","r")
lines=combo.readlines()
However, the data is then appears as
lines=['Soup\tTomato\r\n','Beans\tKidney\r\n',...]
I would like each entry to be its own element in the list, like
lines=['Soup','Tomato',...]
And even better would be to have two lists, one for each column.
Can someone suggest a way to achieve this or fix my problem?
You should split the lines:
lines = [a_line.strip().split() for a_line in combo.readlines()]
Or without using readlines:
lines = [a_line.strip().split() for a_line in combo]
You look like your opening a csv tab delimeted file.
use the python csv class.
lines = []
with open('combo.txt', 'rb') as csvfile:
for row in csv.reader(csvfile, delimiter='\t'):
lines += row
print(lines)
now as a list.
or with a list of lists you can invert it ...
lines = []
with open('combo.txt', 'rb') as csvfile:
for row in csv.reader(csvfile, delimiter='\t'):
line.append(rows) # gives you a list of lists.
columns = map(list, zip(*lines))
columns[0] = ['Soup','Beans',...];
If you want to get all the items in a single list:
>>> with open('combo.txt','r') as f:
... all_soup = f.read().split()
...
>>> all_soup
['Soup', 'Tomato', 'Beans', 'Kidney']
If you want to get each column, then do this:
>>> with open('combo.txt','r') as f:
... all_cols = zip(*(line.strip().split() for line in f))
...
>>> all_cols
[('Soup', 'Beans'), ('Tomato', 'Kidney')]
Use the csv module to handle csv-like files (in this case, tab-separated values, not comma-separated values).
import csv
import itertools
with open('path/to/file.tsv') as tsvfile:
reader = csv.reader(tsvfile, delimiter="\t")
result = list(itertools.chain.from_iterable(reader))
csv.reader turns your file into a list of lists, essentially:
def reader(file, delimiter=",")
with open('path/to/file.tst') as tsvfile:
result = []
for line in tsvfile:
sublst = line.strip().split(delimiter)
result += sublst
return result

This is a follow up to another post I had on splitting using Python

Before I was not able to get the split to work. Now it is working but only performing the calculation on the last list of the list of list. I need it to calculate the efficiency on each of the players not just the last one in the file.
I am thinking a while loop before the calculation might solve my problem, but I am open to suggestions.
def get_data_list (file_name):
data_file = open(file_name, "r")
data_list = []
for line_str in data_file:
# strip end-of-line, split on commas, and append items to list
data_list =line_str.strip().split(',')
gp=int(data_list[6])
mins=int(data_list[7])
pts=int(data_list[8])
oreb=int(data_list[9])
dreb=int(data_list[10])
reb=int(data_list[11])
asts=int(data_list[12])
stl=int(data_list[13])
blk=int(data_list[14])
to=int(data_list[15])
pf=int(data_list[16])
fga=int(data_list[17])
fgm=int(data_list[18])
fta=int(data_list[19])
ftm=int(data_list[20])
tpa=int(data_list[21])
tpm=int(data_list[22])
efficiency = ((pts+reb+asts+stl+blk)-((fga-fgm)+(fta-ftm)+to))/gp
data_list.append (efficiency)
return data_list
file_name1 = input("File name: ")
result_list = get_data_list (file_name1)
print(result_list)
Thanks in advance for your help.
You're redefining data_list in each iteration:
data_list = []
for line_str in data_file:
# strip end-of-line, split on commas, and append items to list
data_list =line_str.strip().split(',')
Try changing the first data_list to something like data = []. Also, you can use with when opening your file so that things like closing are handled properly:
def get_data_list (file_name):
with open(file_name, "r") as data_file:
data = []
for line_str in data_file:
# strip end-of-line, split on commas, and append items to list
data_list =line_str.strip().split(',')
# Your definitions here...
gp=int(data_list[6])
# ...
efficiency = ((pts+reb+asts+stl+blk)-((fga-fgm)+(fta-ftm)+to))/gp
data_list.append (efficiency)
data.append(data_list)
return data
However you could also look into the csv module - it looks like you're dealing with comma-separated values, and that module provides a very nice interface for handling them.

Categories

Resources