I need help with a problem concerning the code below.
with open ("Premier_League.txt", "r+") as f:
i= int(input("Please put in your result! \n"))
data = f.readlines()
print(data)
data[i] = int(data[i])+1
f.seek(0) # <-- rewind to the beginning
f.writelines(str(data))
f.truncate() # <-- cut any leftovers from the old version
print(data)
data[i] = str(data)
For example if the file
Premier_League.txt contains:
1
2
3
and as I run the program and choose i as 0
that gives me:
[2, '2\n', '3']
and saves it to the already existing file (and deletes the old content)
But after that I cannot run the program again and it gives me this:
ValueError: invalid literal for int() with base 10: "[2, '2\\n', '3']"
My question is: How do I make the new file content suitable to go into the program again?
I recommend this approach:
with open('Premier_League.txt', 'r+') as f:
data = [int(line.strip()) for line in f.readlines()] # [1, 2, 3]
f.seek(0)
i = int(input("Please put in your result! \n"))
data[i] += 1 # e.g. if i = 1, data now [1, 3, 3]
for line in data:
f.write(str(line) + "\n")
f.truncate()
f readlines() read all content in a list as a string,if you want write back those contents as int
data=[]
with open ("Premier_League.txt", "r+") as f:
i= int(input("Please put in your result! \n"))
data = f.readlines()
with open ("Premier_League.txt", "w") as f:
for j in data:
f.write(str(int(j)+1))
#or do this to make it more clean,these lines are comments
#j=int(j)+1
#f.write(str(j))
# <-- cut any leftovers from the old version
print(data)
Note that,once you open a file,if you don't close it,your written contents can be lost,whatever you want to do with data,your have to do it in the second writing method .Also notice the change from r to w in with open ("Premier_League.txt", "w") for writing
Following my solution:
with open ("Premier_League.txt", "r+") as f:
i= int(input("Please put in your result! \n"))
# here strip wrong chars from input
data = f.readlines()
print(data)
# here added the str(..) conversion
data[i] = str(int(data[i].strip())+1) + '\n'
f.seek(0) # <-- rewind to the beginning
# the str(data) is wrong, data is a list!
f.writelines(data)
# I don't think this is necessary
# f.truncate() # <-- cut any leftovers from the old version
print(data)
# i think this is not necessary
# data[i] = str(data)
Related
So I have finally succeeded in making it so that I can read from my text file and add it to a list. But now I have the slight problem of each value looks like this 6\n. How do I fix this do I need to restructure my code.
Below is the code.
The error:
Number guessing game with highscores.py", line 42, in <module>
highscoreS = [highscores.replace("\n", "") for highscores in highscoreS]
NameError: name 'highscoreS' is not defined
Even though I have clearly defined it
from random import randint
a = True
n = randint(1,10)
guesses = 0
#If scores ever need to be reset just run function
def overwritefile():
f = open("Numbergame.txt", "w")
f.close()
#overwritefile()
#Guessing Game Code
while a == True:
guess = int(input("What is your guess? \nEnter a number!"))
if guess > n:
print("Guess is too high! \nTry Again!")
guesses += 1
elif guess < n:
print("Guess is too low! \nTry Again!")
guesses += 1
else:
guesses += 1
a = False
print("You guessed the number! \nIt was " + str(n) + "\nIt took you: " + str(guesses) + " guesses")
#Adding Score to the file
f = open("Numbergame.txt", "a")
f.write(str(guesses) + '\n')
f.close()
highscores = []
#Compare values and figure out if it is a new highscore
#Maybe I will use the TRY thing got taught recently might help iron out some errors
#f = open("Numbergame.txt").readlines()
with open('Numbergame.txt', 'rt') as f:
for highscore in f:
highscores.append(highscore)
highscoreS = [highscores.replace('\n', '') for highscores in highscoreS]
"Even though I have clearly defined it"
You need to have defined it before it's used. As of now, highscoreS is used in the same line that it is defined. The correct way would be to read all values into a list first, and then use the list you defined.
highscores = []
with open('Numbergame.txt', 'rt') as f:
for line in f:
highscores.append(line)
# Notice this is OUTSIDE the loop
highscoreS = [hs.replace('\n', '') for hs in highscores]
To overwrite the original highscores, you can do
highscores = [hs.replace('\n', '') for hs in highscores]
However, this is unnecessarily convoluted. Instead of doing it this way, I suggest you simply strip() the whitespace when you read the score.
highscores = []
with open('Numbergame.txt', 'rt') as f:
for line in f:
highscores.append(line.strip()) # Or line.replace('\n', '')
You also probably want to convert the values to integers, in which case it makes sense to also do that in the loop when you read the lines from the file.
highscores = []
with open('Numbergame.txt', 'rt') as f:
for line in f:
highscores.append(int(line)) # No need to strip because `int()` automatically takes care of that
You can condense this down even more into a pythonic list comprehension, as #tdelaney mentioned:
with open('Numbergame.txt', 'rt') as f:
highscores = [int(line) for line in f]
i would like to know how i could get all lines after the first in a python file
I've tried with this:
fr = open("numeri.txt", "r")
count = 0
while True:
line = fr.readline(count)
if line == "":
break
count += 1
print(line)
fr.close()
Could anyone help me? Thanks
You could add an extra if statement to check if count != 0 Since on the first loop it will be 0.
I don't know if i understood well, but to obtain all the lines skipping the first one you can simple do
lines = []
with open("numeri.txt") as fobj:
lines = fobj.readlines()[1:]
count = len(lines)+1 if lines else 0 # If you want to maintain the same counting as in your example
count = 0
with open(file, 'r') as file:
next(file.readline()) # skip the first line
for count, line in enumerate(file.readlines()): # read remaining lines with count
if not line: # If line equals "" this will be True
break
print(count, line)
count -= 1 # To ignore last lines count.
Just read the first line without using it:
with open('numeri.txt') as f:
f.readline()
lines = f.readlines()
print(*lines, sep='')
To ignore the first line you can also use next(f) (instead of f.readline()).
This is also fine:
with open('numeri.txt') as f:
lines = f.readlines()[1:]
print(*lines, sep='')
Try using l[1:]. It returns a subset of l that consist in the elements of l except the first position.
with open("numeri.txt", "r") as f:
content = f.readlines()[1:]
for line in content:
print(line.strip('\n')) # In order to avoid introduce double \n since print ends with a '\n'
EDIT: Based on #riccardo-bucco ' solution:
with open("numeri.txt", "r") as f:
content = f.readlines()[1:]
print(*content, sep='')
To print all but the first line:
with open('numeri.txt', 'r') as f:
output = ''.join(f.readlines()[1:])
print(output)
start count at 1 so it skips the first line
...
count = 1
...
I need to write a program that reads a file containing a list of floating-point numbers and counts how many of those numbers are larger than a user-specified threshold.
numbers.txt -
5.0
15.0
25.0
This is my python code -
in_file = open("numbers.txt", "r")
number = float(in_file.read()) # error in python
user_input = float(input("Threshold: "))
if number > user_input:
print(number)
in_file.close()
Python is unable to convert the string to a float because the numbers have a new line after each number and python is trying to convert that into a float. I tried to change line 2 in my code to add a strip method but it still comes up with the same error.
for line in open("numbers.txt", "r"):
line = line.replace("\n","")
num = float(line)
im sure you can continue from here..
Try this:
with open('numbers.txt') as fp:
lst = [float(line.strip()) for line in fp if line.strip()]
user_input = float(input("Threshold: "))
for num in lst:
if num > user_input:
print(num)
You can try this workaround
inputdata = []
with open('data.txt') as f:
for row in f:
try:
number = float(row)
inputdata.append(number)
except:
pass
I am trying to get a to be the first line of the file and b to be the second.
This prints nothing.
f = open(filename)
line = f.readline().strip()
while line:
a = f.readline()
b = f.readline()
line = f.readline()
print(a)
print(b)
I want to assign specific lines to variables, not just read all of them.
Check the tutorial first please, it says:
If you want to read all the lines of a file in a list you can also use
list(f) or f.readlines().
lines = f.readlines()
a = lines[0]
b = lines[1]
lines =[]
with open(filename) as f:
i =0
for line in f:
lines[i] = line
i += 1
print '1st Line is: ', lines[0]
print '2st Line is: ', lines[1]
When I'm reading a line in a text file, like this one below :
présenté alloué ééé ààà tué
And try to print it in the terminal, it displays correctly. But when I apply a split with a space as separator, it displays this :
['pr\xc3\xa9sent\xc3\xa9', 'allou\xc3\xa9', '\xc3\xa9\xc3\xa9\xc3\xa9', '\xc3\xa0\xc3\xa0\xc3\xa0', 'tu\xc3\xa9\n']
I just use this to read the text file :
f = open("test.txt")
l = f.readline()
f.close()
print l.split(" ")
Can someone help me ?
Printing the list is not the same as printing its elements
s = "présenté alloué ééé ààà tué"
print s.split(" ")
for x in s.split(" "):
print x
Output:
['pr\xc3\xa9sent\xc3\xa9', 'allou\xc3\xa9', '\xc3\xa9\xc3\xa9\xc3\xa9', '\xc3\xa0\xc3\xa0\xc3\xa0', 'tu\xc3\xa9']
présenté
alloué
ééé
ààà
tué
Python 3.* solution:
All you have to do is to specify the encoding you wish to use
f = open("test.txt", encoding='utf-8')
l = f.readline()
f.close()
print(l.split(" "))
And you'll get
['présenté', 'alloué', 'ééé', 'ààà', 'tué']
Python 2.* solution:
import codecs
f = codecs.open("""D:\Source Code\\voc-git\\test.txt""", mode='r', encoding='utf-8')
l = f.read()
f.close()
for word in l.split(" "):
print(word)