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')]
Related
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())
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:
Python: read all text file lines in loop
(5 answers)
Closed 8 years ago.
A situation that I continually run into is the following:
readFile = open("myFile.txt", "r")
while True:
readLine = readFile.readline()
if readLine == "":
#Assume end of file
break
#Otherwise, do something with the line
#...
The problem is that the file I am reading contains blank lines. According to the documentation I have read, file.readline() will return "\n" for a blank line found in a file, but that does not happen for me. If I don't put that blank line condition in the while loop, it continues infinitely, because a readline() executed at or beyond the end of the file returns a blank string.
Can somebody help me create a condition that allows the program to read blank lines, but to stop when it reaches the end of the file?
Just use a for loop:
for readLine in open("myFile.txt"):
print(readLine); # Displayes your line contents - should also display "\n"
# Do something more
Stops automatically at end of file.
If you sometimes need an extra line, something like this might work:
with open("myFile.txt") as f:
for line in f:
if needs_extra_line(line): # Implement this yourself :-)
line += next(f) # Add next line to this one
print(line)
Or a generator that yields the chunks you want to use:
def chunks(file_object):
for line in file_object:
if needs_extra_line(line):
line += next(file_object)
yield line
Then the function that processes the lines can run a for loop over that generator.
This question already has answers here:
readlines gives me additional linebreaks python2.6.5
(3 answers)
Closed 8 years ago.
I'm reading strings from lines in a text file and then putting them into a list, simple enough. However when I return the List, the strings have a new line character at the end of them. When i try printing a value individually with print list[0] for example the new line character will not be present. How do I make it so the list values don't have newline characters in them to begin with? Why is this happening anyway?
Edit: I didn't think code would matter but even in the following i will have problems:
file = open("test.txt", "U")
test = []
for line in file:
line.rstrip()
test.append(line)
print test
Update: I looked up stripping new line characters and using .rstrip() doesn't work
you can try
file = open("test.txt", "U")
test = []
for line in file:
line = line.replace("\r\n","").replace("\n","")
test.append(line)
print test
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Replace four letter word in python
I want write a file in the python shell, run a program in it, and then close the file.
Here is the code I have right now.
def censor(fileName):
file = open(fileName, "r")
for i in len(myList):
censoredFile = open("censored.txt", "w")
outputFile.write(censoredFile)
outputFile.close()
The program I want to run isn't in the program yet because I'm just trying to figure out how to deal with files. I have some programming experience but not a lot with files. Any input would be appreciated.
Thanks!
This is the code you need to read a file, replace all the four letter word and write the final result into a different file.
def censor(fileName):
output_content = ""
with open(fileName, "r") as input_file:
with open("censored.txt", "w") as output_file:
output_content = ""
for line in input_file:
output_content += ' '.join([word if len(word) != 4 else "****" for word in line.split(" ")])
output_file.write(output_content)
It should be it.
def censor(fileName):
censoredFile = open("censored.txt", "w")
for line in open(fileName, "r"):
censoredLine= do_stuff_to_censor_line(line)
censoredFile.write(censoredLine)
In plain english here is what the function does:
1. open the output file
2. go through the input file... for each line:
2.1 figure out what the censored version of the line would be
2.2 write the censored version of the line to the output file
3. close both files (this happens automatically so you dont actually have to call close()
Now for the actual censoring of a line...
Just looking at 4 letter words is probably not powerful enough if you want to censor stuff properly. This is because not all naughty words are four letters long. There are also some not-naughty words that are four letters long [eg: 'four','long','want','this','help']
def do_stuff_to_censor_line(line):
list_of_naughty_words = ['naughty_word_1','naughty_word_2','etc']
for naughty_word in list_of_naughty_words:
line.replace(naughty_word,'*$##!')
return line
I'll leave it up to you to deal with different capitalizations...