Here there is already a similar question, but I need a solution that does not involve connecting the csv module. File to read:

Петров;85;92 Сидоров;100;88 Иванов;58;72 

It is required to display the average value of the first and second pairs of values ​​under each name. I try to do it like this:

 file = open('In.txt', 'r') for line in file: [print((first + second)/2) for name, first, second in line.split(';')] 

But this design does not work. How to divide a string, obtained in a loop from a file by a symbol ; ?

  • you basically can not use any modules? - MaxU
  • @MaxU is not desirable, because I am only learning this wonderful language and I want to be able to use the built-in functionality sufficiently - AlexIdest

1 answer 1

 filename = r'C:\Temp\data.csv' sep = ';' with open(filename, encoding='utf-8') as f: for line in f: vals = line.strip().split(sep) avg = sum(map(float, vals[1:])) / len(vals[1:]) print(f"{vals[0]}: {avg}") 

Output on display:

 Петров: 88.5 Сидоров: 94.0 Иванов: 65.0 

PS The decision is based on the fact that in the first column is the name (string), and in the remaining columns are numerical values. For each row is the average for all columns except the first.

  • csv is a binary file, right? Does reading binary files work in the same way as txt format? - AlexIdest
  • 6
    @AlexIdest, CSV is a text file - MaxU
  • @AlexIdest any file is binary, the only question is whether these binary files can be interpreted as text in some encoding. The code for this response implies that the text is in utf-8 encoding. Well, yes, csv is the text - andreymal