简体   繁体   中英

Python reading file problems

highest_score = 0
g = open("grades_single.txt","r")
arrayList = []
for line in highest_score:
    if float(highest_score) > highest_score:
       arrayList.extend(line.split())
g.close()

print(highest_score)

Hello, wondered if anyone could help me , I'm having problems here. I have to read in a file of which contains 3 lines. First line is no use and nor is the 3rd. The second contains a list of letters, to which I have to pull them out (for instance all the As all the Bs all the Cs all the way upto G) there are multiple letters of each. I have to be able to count how many off each through this program. I'm very new to this so please bear with me if the coding created is wrong. Just wondered if anyone could point me in the right direction of how to pull out these letters on the second line and count them. I then have to do a mathamatical function with these letters but I hope to work that out for myself.

Sample of the data:

GTSDF60000
ADCBCBBCADEBCCBADGAACDCCBEDCBACCFEABBCBBBCCEAABCBB
*

You do not read the contents of the file. To do so use the .read() or .readlines() method on your opened file. .readlines() reads each line in a file seperately like so:

g = open("grades_single.txt","r")
filecontent = g.readlines()

since it is good practice to directly close your file after opening it and reading its contents, directly follow with:

g.close()

another option would be:

with open("grades_single.txt","r") as g:
    content = g.readlines()

the with -statement closes the file for you (so you don't need to use the .close() -method this way. Since you need the contents of the second line only you can choose that one directly:

    content = g.readlines()[1]

.readlines() doesn't strip a line of is newline(which usually is: \\n ), so you still have to do so:

    content = g.readlines()[1].strip('\n')

The .count() -method lets you count items in a list or in a string. So you could do:

dct = {}
for item in content:
    dct[item] = content.count(item)

this can be made more efficient by using a dictionary-comprehension:

dct = {item:content.count(item) for item in content}

at last you can get the highest score and print it:

highest_score = max(dct.values())
print(highest_score)

.values() returns the values of a dictionary and max, well, returns the maximum value in a list.

Thus the code that does what you're looking for could be:

with open("grades_single.txt","r") as g:
    content = g.readlines()[1].strip('\n')

dct = {item:content.count(item) for item in content}

highest_score = max(dct.values())
print(highest_score)

To count the occurrences of each letter I used a dictionary instead of a list. With a dictionary, you can access each letter count later on.

d = {}
g = open("grades_single.txt", "r")
for i,line in enumerate(g):
    if i == 1:
        holder = list(line.strip()) 
g.close()

for letter in holder:
    d[letter] = holder.count(letter)

for key,value in d.iteritems():
    print("{},{}").format(key,value)

Outputs

A,9
C,15
B,15
E,4
D,5
G,1
F,1
import re


# opens the file in read mode (and closes it automatically when done)
with open('my_file.txt', 'r') as opened_file:

    # Temporarily stores all lines of the file here.
    all_lines_list = []

    for line in opened_file.readlines():
        all_lines_list.append(line)

    # This is the selected pattern.
    # It basically means "match a single character from a to g"
    # and ignores upper or lower case
    pattern = re.compile(r'[a-g]', re.IGNORECASE)

    # Which line i want to choose (assuming you only need one line chosen)
    line_num_i_need = 2

    # (1 is deducted since the first element in python has index 0)
    matches = re.findall(pattern, all_lines_list[line_num_i_need-1])

    print('\nMatches found:')
    print(matches)
    print('\nTotal matches:')
    print(len(matches))

You might want to check regular expressions in case you need some more complex pattern.

highest_score = 0
arrayList = []
with open("grades_single.txt") as f:
    arraylist.extend(f[1])
print (arrayList)

This will show you the second line of that file. It will extend arrayList then you can do whatever you want with that list.

One can treat the first line specially (and in this case ignore it) with next inside try: except StopIteration: . In this case, where you only want the second line, follow with another next instead of a for loop.

with open("grades_single.txt") as f:
    try:
        next(f)  # discard 1st line
        line = next(f)
    except StopIteration:
        raise ValueError('file does not even have two lines')

# now use line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM