#๐ subdivide a txt file
224 messages ยท Page 1 of 1 (latest)
@frigid wharf
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
@frigid wharf You can't upload files here. Use a paste link if you'd like to share code
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Not a problem!
https://paste.pythondiscord.com/3PBA I have this txt file with some fake data in it
I have to work with it and do operation like "print all student in base of theyr age"
"order in alphabetical order" "print users in base of class"
What code have you written so far?
Not much (zero)
Is there anything from this you do know how to do?
I don't know where to start
I know I can open txt file with open file as f
That's a good place to start
I know the functions read, readline and readlines
I know the basic built in function such as split()
it's always best to dive in with what you do know and then you can work around any issues you have
but a blank python document is far scarier
start with opening the file
I have it opened
with python
Yes
ok, and you said you know how to split, so split the lines of the file
I know I can split a list
you can't split a list
you can split a string into a list
Yeah sorry
!e
line = '1 B LUCA CAVALLI 14/04/2007'
print(line.split())
@analog heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
['1', 'B', 'LUCA', 'CAVALLI', '14/04/2007']
How can I use this?
so for example, here's one line of your file
Oh wait I have an idea
this perfectly splits it into number, letter, first name, last name, date
line = f.readline()
line.split()
since you're going to want to want every line, you're better off using readlines()
that will load all the lines into a list which you can then iterate
or even for line in f:
But readlines give me a list
yes, which you can use a for loop with
Oh I can out it in a for and take thing
And then take the first element (class) and put in a class list?
there's no need to separate the elements
one student is represented in 1 line of text
you can have a list of lists of students
This is eventually what you want to end up with
a list of lists
oh its alredy subdived
I'm not sure what you mean by that?
I'm showing you the result you want to get. There's a few steps required to get to this point
lets say i want to print the name in order
don't worry about the ordering yet
oh its not alredy did with readlines?
we're focusing on one thing at a time
no, readlines access each line. You still need to split each line to get the data within
i honestly dont know how to do it
with readlines and split
i have an idea but it seems usless
you said you know how readlines works, and how split works
always show what you try
and always try
readlines give me a list, i cant split a list
.
you've already said what you need to do with that list
you have a list of strings
readlines gives you a list of strings
we will work with it
you can use a for loop on that list
yes, it's very hard to help you adjust code if you aren't sharing it
sorry
thats line.split(" ") for each line aint it
yup!
It's being appended to a new list as well to store them
I'd like to walk through the logic of a for loop without list comp for now
tbh i didnt understand
show what you tried
you said you understand readlines, and split, so it's hard to figure out what part you're stuck at
split it into lines and iterate over that
i was trung to work with one line at time to test
That's a good start
you can access every line in a file by simply doing for line in file
so if you had a for loop that does this, you don't really have to change much else about your code
the code dosent seem to work
yes, it works perfectly for 1 line
why the space becomed \t?
oh
dosent seem
why does it do this?
oh
give me a second i have an huge idea
ok it dosent work
lines = [] # empty matrix
with open("dati_alunni.txt", "r") as file:
for i in range(len(file.readlines())):
line = file.readline() # read line by line
if line != "": # for empty lines
line.split() # split in list
lines.append(line) # add list to matrix
print(lines)```
this is my code, lines is an empty list
no need to use range here
i never used a for without it, so idk
and no need to use readline AND readlines
I've mentioned multiple times above how you can use it
.
i understand but if i copy code you can do my homework and send directly to the teacher
i want to understand, not to copy things
that's why I'm not handing you the solution
but I'm hoping you can piece together what I'm telling/showing you
loop through file
split line
append line to list of students
that's all you need to do, you're overthinking it a bit
i have an idea
lines = [] # empty matrix
with open("dati_alunni.txt", "r") as file:
for line in file.readlines():
if line != "": # for empty lines
line.split("\t") # split in list
lines.append(line) # add list to matrix
print(lines)```
but it dosent work
when you do line.split, it simply returns the new list, it won't actually modify the data that line represents
you can either create a new variable, or append it in 1 line
lines.append(line.split())
oh yeah i am stupid i forgot
I still really recommend using split() instead of split("\t")
yes, you have a list of lists now
I'd also recommend naming your variable something a bit different so it's less confusing
students might make more sense than lines
always try and be meaningful with your var names
i have one idea to continue
yeah sorry, i usually do that
but sometimes i forgot if the code is small
students_info = [] # empty matrix
with open("dati_alunni.txt", "r") as file:
for line in file.readlines():
if line != "": # for empty lines
line = line.split() # split in list
students_info.append(line) # add list to matrix
print(students_info)```
what do i do now?
something that i know is the fact that in this matrix the first element of each list is always the class
the second the section etc
so if i do students_info[i][j]
and put i/j with a fixed value
i can get all the row
am i right?
exactly, this is very useful
do you know how to sort a list?
yes
.sort(order, key)
first thing that i want to do its to sort all the names, right?
do you know how to use the key?
i dont think i need it
you do need it if you want to sort by names
my idea was a little different
since i dont know how to use key (i never used it in class, i just know it exist) i was thinking to use ascii
the key is how we can tell python by which information to sort the list
in this case, we can use the key to tell it to sort by name
how can we use it?
and do you know what return does in a function?
ok, so when we use key to sort something, we're basically telling it a specific function to call on every item in the list. The list will then be sorted by the return of this function
['1', 'A', 'VIOLA', 'ROSSI', '12/05/2007']
do you want to sort by last name or first name?
last name
ok, which index of this list is that?
3
exactly
def sort_last_name(student):
you can define a function like this which we'll eventually use as the sort key
the information it will receive is 1 student (a list of information about that student)
if we return student[3], we're telling it each student should be sorted by last name
def sort_last_name(student):
return student[3]
everything is already exactly as it should be up until this point
you don't have to do any more splitting
!e
lista = ["banana", "mela", "pera", "arancia"]
print(lista.sort())```
@frigid wharf :white_check_mark: Your 3.12 eval job has completed with return code 0.
None
there's 2 ways to sort
.sort() and sorted()
.sort() simply sorts the list "in place"
sorted() returns a new list that is sorted
ideally you would actually use sorted() here
!e
lista = ["banana", "mela", "pera", "arancia"]
print(sorted(lista))```
@frigid wharf :white_check_mark: Your 3.12 eval job has completed with return code 0.
['arancia', 'banana', 'mela', 'pera']
yes, strings will be sorted alphabetically (although it is case sensitive)
but this is one list of strings
we have a list of a list of strings for the students
why lista.sort() is none and sorted(lista) not?
because sort() doesn't return anything
it's an "in place" operation
it "mutates" the list
!e
lista = ["banana", "mela", "pera", "arancia"]
lista.sort()
print(lista)
@analog heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
['arancia', 'banana', 'mela', 'pera']
Oh ok
I have to options: use the key or make a list with all names
Right?
Sorry for late reply
you could, but that's extra steps
plus what if you want to sort by last name, but still display the rest of their information?
Because key is a little bit hard to understand
def sort_last_name(student):
return student[3]
students = []
with open("people.txt", "r") as file:
for line in file:
students.append(line.split())
for student in sorted(students, key=sort_last_name):
print(student)
Here is everything in action
the function that will be used for sorting is defined at the top
sorted(students, key=sort_last_name)
I don't say that you explanation is bad, just that I don't really understand it much
if my explanation was good, you would understand it ๐
i didnt, sorry..
sort when sorting uses the value returned by the key function for that value so for example the list [1,2,3] with the key def key(x): x[1] vould be sorted as if its value was 2
sorted returns the list list.sort(key=) will sort the list in place and return none thus list.sort()'s value is None but in the place of the original list there will be a sorted list and with sorted sorted()'s value is the sorted list and the original list is unchanged
i honestly didnt understand anything this time
i think its because fo my poor english skills
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.