This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
How do i print each line in a .txt file one by one in a while loop in python
(1 answer)
Closed 3 months ago.
I am making my first game and want to create a score board within a .txt file, however when I try and print the score board it doesn't work.
with open("Scores.txt", "r") as scores:
for i in range(len(score.readlines())):
print(score.readlines(i + 1))
Instead of printing each line of the .txt file as I expected it to instead it just prints []
The contents of the .txt file are:
NAME: AGE: GENDER: SCORE:
I know it's only one line but it should still work shouldn't it?
*Note there are spaces between each word in the .txt file, though Stack Overflow formatting doesn't allow me to show that.
Assign the result of score.readlines() to a variable. Then you can loop through it and index it.
with open("Scores.txt", "r") as scores:
scorelines = scores.readlines()
for line in scorelines:
print(line)
.readlines() reads everything until it reaches the end of the file. Calling it repeatedly will return [] as the file seeker is already at the end.
Try iterating over the file like so:
with open("Scores.txt", "r") as scores:
for line in scores:
print(line.rstrip())
Related
This question already has answers here:
Writelines writes lines without newline, Just fills the file
(8 answers)
Closed 5 months ago.
f= open('elk.in','r')
lines = f.readlines()
for line in lines:
if line.startswith('vkloff'):
p=lines.index(line)+1
#print(lines[p])
break
lines[p] = f'{string}\n'
string=''
with open('elk.in','w') as out:
out.writelines(lines)
out.close()
Here in lines[p] if I remove \n the lines below it get removed. How does it work then?
Taking a few guesses at what your intent here is. You want to open a file, find a line starting with a given prefix, replace it with something else, then write back to the file? There's a few mistakes here if that's the case
You're trying to open a file you already have open. You should close it first.
string is not defined before you use it, assuming this is the full code.
When opening a file using with, you don't need to close it after.
With these in mind you want something like
with open('elk.in','r') as f:
lines = f.readlines()
for idx, line in enumerate(lines):
if line.startswith('vkloff'):
p = idx
break
lines[p] = f'{string}\n'
with open('elk.in','w') as out:
out.writelines(lines)
But really more information is needed about what you're trying to achieve here.
This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 3 years ago.
I want to change my code from read and process from a string of sentence into read from a csv file, and process line by line.
This is my program in VS Code.
import paralleldots
paralleldots.set_api_key("API KEY")
# for single sentence
text="Come on, lets play together"
lang_code="en"
response=paralleldots.sentiment(text,lang_code)
print(response)
I expect the output is run for each line of sentence in a specific csv file, instead of just from a string of sentence.
fp = open('C:/Users/User/Desktop/hj.txt',encoding='utf-8' ,errors='ignore' ) # Open file on read mode
lines = fp.read().split("\n") # Create a list containing all lines
fp.close() # Close file
print(lines)
#print("----------------------------------------------...------\n")
print("\nThe emotion analysis results for each sentence in the file .txt :")
print("------------------------------------------------...------\n")
response=paralleldots.batch_emotion(lines)
print(response)
This worked well.
This question already has answers here:
Why can't I call read() twice on an open file?
(7 answers)
Closed 4 years ago.
I have a file which have some names listed line by line.
gparasha-macOS:python_scripting gparasha$ cat topology_list.txt
First-Topology
Third-topology
Second-Topology
Now I am trying to iterate through these contents, but I am unable to do so.
file = open('topology_list.txt','r')
print file.readlines()
for i in file.readlines():
print "Entered For\n"
print i
topology_list = file.readlines()
print topology_list
file.readlines() prints the lines of the files as a list.
So I am getting this:
['First-Topology\n', 'Third-topology\n', 'Second-Topology\n']
However, When i iterate through this list, I am unable to do so.
Also, when I assign it to a variable 'topology_list' as in the penultimate line and print it. It gives me an empty list.
[]
So I have two questions.
What is wrong with my approach?
How to accomplish this?
The simplest:
with open('topology_list.txt') as topo_file:
for line in topo_file:
print line, # The comma to suppress the extra new line char
Yes, you can iterate through the file handle, no need to call readlines(). This way, on large files, you don't have to read all the lines (that's what readlines() does) at once.
Note that the line variable will contain the trailing new line character, e.g. "this is a line\n"
Change your code like this:
file = open('topology_list.txt','r')
topology_list = file.readlines()
print topology_list
for i in topology_list:
print "Entered For\n"
print i
print topology_list
When you call file.readlines() the file pointer will reach the end of the file. For further calls of the same, the return value will be an empty list.
This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 5 years ago.
How can I tell python to read a txt list line by line?
I'm using .readlines() which doesn't seem to be working.
import itertools
import string
def guess_password(real):
inFile = open('test.txt', 'r')
chars = inFile.readlines()
attempts = 0
for password_length in range(1, 9):
for guess in itertools.product(chars, repeat=password_length):
attempts += 1
guess = ''.join(guess)
if guess == real:
return input('password is {}. found in {} guesses.'.format(guess, attempts))
print(guess, attempts)
print(guess_password(input("Enter password")))
The test.txt file looks like:
1:password1
2:password2
3:password3
4:password4
currently the program only works with the last password on the list (password4)
if any other password is entered it will run past all the passwords on the list and return "none".
So I assume I should be telling python to test each line one at a time?
PS. the "return input()" is an input so that the dialog box doesn't close automatically, there's nothing to be inputted.
readlines returns a list of strings with all remaining lines in the file. As the python docs state you could also use list(inFile) to read all ines (https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects)
But your problem is that python reads the line including the newline character (\n). And only the last line has no newline in your file. So by comparing guess == real you compare 'password1\n' == 'password1' which is False
To remove the newlines use rstrip:
chars = [line.rstrip('\n') for line in inFile]
this line instead of:
chars = inFile.readlines()
First of all try to search duplicated posts.
How do I read a file line-by-line into a list?
For example, what I am usually using when working txt files:
lines = [line.rstrip('\n') for line in open('filename')]
This question already has answers here:
How to read a file without newlines?
(12 answers)
How can I read inputs as numbers?
(10 answers)
Closed 7 months ago.
I'm pretty new to Python, but I'm trying to learn. One idea I had for a simple script was to have a script that reads and writes to a log file during execution. Then based on what's in that log file, helps dictate what the script does the next time it's ran.
Reading and writing to a file seems simple enough in Python,
f = open('textfile.txt', 'r+')
Reading and print out each line of a file seems simple too,
for line in f:
print line
line=f.next()
print line
But, how do I incorporate an IF statement when reading a file to do something based on what was read?
for line in f
if line == '1':
print "Works!"
else:
print line
line=f.next()
print line
f.close()
Output
1
2
3
4
5
The problem is that line is equal to
'1\n'
You first need to remove the newline character by doing first in your loop:
line = line.rstrip()
Another possibility could be, in this particular case in which you expect integers, to cast the line string into an integer, and then to compare to an integer:
line = int(line)
if line == 1:
# and so on