#๐Ÿ”’ subdivide a txt file

224 messages ยท Page 1 of 1 (latest)

abstract inletBOT
#

@frigid wharf

Python help channel opened

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.

analog heath
#

@frigid wharf You can't upload files here. Use a paste link if you'd like to share code

#

!paste

abstract inletBOT
#
Pasting large amounts of code

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.

frigid wharf
#

Oh ok

#

Sorry for my error

analog heath
#

Not a problem!

frigid wharf
#

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"

analog heath
#

What code have you written so far?

frigid wharf
analog heath
#

Is there anything from this you do know how to do?

frigid wharf
#

I don't know where to start

frigid wharf
analog heath
#

That's a good place to start

frigid wharf
#

I know the functions read, readline and readlines

#

I know the basic built in function such as split()

analog heath
#

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

frigid wharf
#

The problem is that I don't know where to start

#

I can write at you my ideas

analog heath
#

start with opening the file

frigid wharf
#

I have it opened

analog heath
#

with python

frigid wharf
#

Yes

analog heath
#

ok, and you said you know how to split, so split the lines of the file

frigid wharf
analog heath
#

you can't split a list

frigid wharf
#

No sorry

#

I string

analog heath
#

you can split a string into a list

frigid wharf
#

Yeah sorry

analog heath
#

!e

line = '1 B LUCA CAVALLI 14/04/2007'

print(line.split())
abstract inletBOT
#

@analog heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

['1', 'B', 'LUCA', 'CAVALLI', '14/04/2007']
frigid wharf
#

How can I use this?

analog heath
#

so for example, here's one line of your file

frigid wharf
#

Oh wait I have an idea

analog heath
#

this perfectly splits it into number, letter, first name, last name, date

frigid wharf
#

line = f.readline()
line.split()

analog heath
#

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:

frigid wharf
#

But readlines give me a list

analog heath
#

yes, which you can use a for loop with

frigid wharf
#

Oh I can out it in a for and take thing

#

And then take the first element (class) and put in a class list?

analog heath
#

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

frigid wharf
#

oh its alredy subdived

analog heath
#

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

frigid wharf
#

lets say i want to print the name in order

analog heath
#

don't worry about the ordering yet

frigid wharf
#

oh its not alredy did with readlines?

analog heath
#

we're focusing on one thing at a time

analog heath
frigid wharf
#

i honestly dont know how to do it

analog heath
#

with readlines and split

frigid wharf
#

i have an idea but it seems usless

analog heath
#

you said you know how readlines works, and how split works

#

always show what you try

#

and always try

frigid wharf
analog heath
#

you've already said what you need to do with that list

#

you have a list of strings

frigid wharf
#

yes but that is for a readline

#

ok let me try to do something

analog heath
#

readlines gives you a list of strings

frigid wharf
#

we will work with it

analog heath
#

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

frigid wharf
#

sorry

cold hull
analog heath
#

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

frigid wharf
#

tbh i didnt understand

analog heath
#

show what you tried

#

you said you understand readlines, and split, so it's hard to figure out what part you're stuck at

cold hull
#

split it into lines and iterate over that

frigid wharf
#

i was trung to work with one line at time to test

analog heath
#

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

frigid wharf
#

the code dosent seem to work

analog heath
#

always share your code

#

unfortunately we aren't mind readers here

frigid wharf
#

mine code

#

the one i gave you in the picture

#

look at output

analog heath
#

yes, it works perfectly for 1 line

frigid wharf
#

why the space becomed \t?

analog heath
#

oh

frigid wharf
analog heath
#

get rid of the ' ' inside split

#

just do split()

#

it will split on any whitespace

cold hull
#

turns out its not space sepearated but tab sepearated instead

#

tabs are "\t"

frigid wharf
#

why does it do this?

frigid wharf
#

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

analog heath
#

no need to use range here

frigid wharf
#

i never used a for without it, so idk

analog heath
#

and no need to use readline AND readlines

#

I've mentioned multiple times above how you can use it

analog heath
frigid wharf
#

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

analog heath
#

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

frigid wharf
#

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

analog heath
#

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

frigid wharf
#

oh yeah i am stupid i forgot

analog heath
#

I still really recommend using split() instead of split("\t")

frigid wharf
#

ok, now i think its working

#

each list is a frase, each lement its a word

#

now?

analog heath
#

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

frigid wharf
#

i have one idea to continue

frigid wharf
#

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?

analog heath
#

do you know how to sort a list?

frigid wharf
#

yes

#

.sort(order, key)

#

first thing that i want to do its to sort all the names, right?

analog heath
#

do you know how to use the key?

frigid wharf
#

i dont think i need it

analog heath
#

you do need it if you want to sort by names

frigid wharf
#

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

analog heath
#

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

frigid wharf
#

how can we use it?

analog heath
#

have you learned about defining your own functions?

#

or lambda?

frigid wharf
#

yes

#

def name(argoument):

analog heath
#

and do you know what return does in a function?

frigid wharf
#

yes

#

close it and return a value intro a variable

analog heath
#

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?

frigid wharf
#

last name

analog heath
#

ok, which index of this list is that?

frigid wharf
#

3

analog heath
#

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]
frigid wharf
#

oh

#

but does split knwo to split names?

#

because i tryed with a list

#

wait

analog heath
#

everything is already exactly as it should be up until this point

#

you don't have to do any more splitting

frigid wharf
#

!e

lista = ["banana", "mela", "pera", "arancia"]

print(lista.sort())```
abstract inletBOT
#

@frigid wharf :white_check_mark: Your 3.12 eval job has completed with return code 0.

None
analog heath
#

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

frigid wharf
#

!e

lista = ["banana", "mela", "pera", "arancia"]

print(sorted(lista))```
abstract inletBOT
#

@frigid wharf :white_check_mark: Your 3.12 eval job has completed with return code 0.

['arancia', 'banana', 'mela', 'pera']
analog heath
#

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

frigid wharf
#

why lista.sort() is none and sorted(lista) not?

analog heath
#

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)
abstract inletBOT
#

@analog heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

['arancia', 'banana', 'mela', 'pera']
frigid wharf
#

I have to options: use the key or make a list with all names

#

Right?

#

Sorry for late reply

analog heath
#

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?

frigid wharf
#

Because key is a little bit hard to understand

analog heath
#
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)
frigid wharf
#

I don't say that you explanation is bad, just that I don't really understand it much

analog heath
#

if my explanation was good, you would understand it ๐Ÿ™‚

frigid wharf
cold hull
#

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

frigid wharf
#

i honestly didnt understand anything this time

#

i think its because fo my poor english skills

abstract inletBOT
#
Python help channel closed

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.