Question: How can I use the f.readline()
functions on replit?
I’d like to run these commands,
ligne = f.readline()
while ligne != "":
ville = Ville(ligne.split(","))
liste_villes.append(ville)
ligne = f.readline()
But pyright returns: Cannot access member "readline" for type "_reader" Member "readline" is unknown
And how can I use a file that has already been uploaded to replit in files?
For example, the file villes.csv, how to use it in the main.py?
Repl link: https://replit.com/@MichaelDai2/TP-ABR-classer-des-villes-selon-differents-criteres#main.py
https://replit.com/@MichaelDai2/TP-ABR-classer-des-villes-selon-differents-criteres#main.py
csv readers do not have a readline method because they are not file-like objects.
Instead, you should iterate over them with a for
loop or iterate over them manually with next
function to get the lines (in list of strings form).
In your while loop, you exit when a row is empty without reading the rest of the file. Is this intended? If so,
ligne = next(f)
while ligne: # empty lists are falsy
ville = Ville(ligne)
liste_villes.append(ville)
ligne = next(f)
If not, and you are just trying to filter out empty rows,
liste_villes = [Ville(ligne) for ligne in f if ligne]
Also:
You are opening a file (csvfile
) and then using it to create a reader, enclosed in a with
statement. However, it doesn’t appear that you are ever making a copy of the file before it is automatically closed at the end of the with
statement. This might cause problems because the reader is trying to use a file that’s been closed.
Therefore, you should put all of the code using the csv reader in the with
statement too.
Pyright helps detect bugs in your code and sometimes it is correct (as in this case), and sometimes it is wrong and can be safely ignored.
2 Likes
You can use files by right clicking the file and copying the file path. Put the file path in the Python open
function and you can access it.
Code example:
import csv
with open("text.txt","r") as file:
csv=csv.reader(file, delimiter=",")
for row in csv:
print(row)
1 Like