Forum Archive

Help with opening files in phythonista

Ald

Hi folks

I am new to phythonista, iPad and Python. I need the following code to open up a text file in the script folder of pythonista :

scores = {}
result_f = open("results.txt")
for line in result_f:
(name, score) = line.split()
scores[score] = name
result_f.close()
print("the top scores were:")
for each_score in scores.keys():
print('surfer' + scores[each_score]+'scored'+each_score)

The contents of results.txt is:
Johnny 8.65
Juan 9.12
Joseph 8.45
Stacey 7.81
Aideen 8.05
Zack 7.21
Aaron 8.31

ccc

To format the Python code in your post above...

  • Enter a blank line with no text
  • Enter a line containing only: ```python
  • Enter your Python code
  • Enter a line containing only: ```

The ` character is a backtick or accent grave character which you can get by doing a tap and hold on the ' keyboard key.

Ald

' ' 'python
scores = {}
result_f = open("results.txt")
for line in result_f:
(name, score) = line.split()
scores[score] = name
result_f.close()
print("the top scores were:")
for each_score in scores.keys():
print('surfer' + scores[each_score]+'scored'+each_score)
' ' '

Ald

Thanks

Ald

`python

scores = {}
result_f = open("results.txt")
for line in result_f:
(name, score) = line.split()
scores[score] = name
result_f.close()
print("the top scores were:")
for each_score in scores.keys():
print('surfer' + scores[each_score]+'scored'+each_score)
`

ccc

Put a carrage return after the word python.

Ald

Let's try


[scores = {}
result_f = open("results.txt")
for line in result_f:
    (name, score) = line.split()
    scores[score] = name
result_f.close()
print("the top scores were:")
for each_score in scores.keys():
    print('surfer' + scores[each_score]+'scored'+each_score)]

`python

scores = {}
result_f = open("results.txt")
for line in result_f:
(name, score) = line.split()
scores[score] = name
result_f.close()
print("the top scores were:")
for each_score in scores.keys():
print('surfer' + scores[each_score]+'scored'+each_score)

`

Ald

Don't think that worked either

dgelessus

Copy-paste the following and insert your code:

```

[your code here]

```

There has to be a blank line above the first and after the last three backticks. If you want Python syntax highlighting, add python directly after the first three backticks, with no space in between, on the same line.

ccc

@Ald, your code looks good to me:

scores = {}
result_f = open("results.txt")
for line in result_f:
    (name, score) = line.split()
    scores[score] = name
result_f.close()
print("the top scores were:")
for each_score in scores.keys():
    print('surfer ' + scores[each_score] + ' scored ' + each_score)

# or an alternate formulation:

def get_scores_dict(file_name):
    with open(file_name) as in_file:
        return {k:v for k,v in [line.split() for line in in_file]}

scores_dict = get_scores_dict('results.txt')
print('The top {} scores were:'.format(len(scores_dict)))
for player in sorted(scores_dict):
    print('surfer {} scored {}'.format(player, scores_dict[player]))

Seem to work as expected if results.txt contains:

Johnny 8.65
Juan   9.12
Joseph 8.45
Stacey 7.81
Aideen 8.05
Zack   7.21
Aaron  8.31

A few notes on the alternate version:

  • It creates a separate function to build a dict from a file to increase the likelihood of reuse elsewhere.
  • It uses the with open() syntax which is generally preferred because it automatically calls .close() for you.
  • It uses both a list comprehension and a dict comprehension which are quite optimized but can be confusing.
  • It uses sorted() to put the players into alphabetical order (although score order might be even more useful).
  • It drops the use of .keys() which is optional when iterating thru all of the items in a dict.
  • It uses str.format() which is the generally preferred way to build up strings because it is more efficient than concatenation (+).

NOTE: In the upper right of each of your posts to this forum is the word edit which you can tap to modify your post.

Ald

Wow thanks for that. I will learn a lot from the second method. I am going through a book called head first programming and just doing all the tutorials.

Ok it also seems as if the code I insert must be inserted within [] as pointed out to me kindly above.

Ald

Ok it works now, it turns out my results.txt file had some blank lines at the end that obviously caused the trouble

ccc

Cool. To gracefully deal with (i.e. ignore) blank or whitespace-only lines in the input file, make the following change in the alternate formulation above.

# change the line:
        return {k:v for k,v in [line.split() for line in in_file]}
# to:
        return {k:v for k,v in [line.split() for line in in_file if line.strip()]}

Surrounding your code with [ and ] should not be required to get formated text in the forum.

Ald

You are a top guy! Thanks for the tips and help.