Python if Statement Not Recognizing Variable Loaded From A Text File [duplicate] - python

This question already has answers here:
String comparison doesn't seem to work for lines read from a file
(2 answers)
Closed 1 year ago.
So I have a text file called Subject.txt with the contents "Fiction" (no quotations) inside it. One line, nothing else.
Using:
file = open("Subject.txt", "r")
Subject = (file.read())
file.close()
This writes the contents to a variable called Subject, which seems verified when I used
print(Subject)
and it returns Fiction as the response.
But this code...
if Subject == "Fiction":
print("Yes")
else:
print("No")
...gets me the No response, not the Yes. If I were to manually create the variable the long way...
Subject = "Fiction"
if Subject == "Fiction":
print("Yes")
else:
print("No")
...I get Yes.
But loaded from the text file, I don't. I need to create variables from text files, if possible, and I was trying to test that I got it right. I'm missing something.
So what am I doing wrong here?

You're probably reading a newline character (\n) at the end of the file and it is being saved to your variable...
In order to get rid of this character, use the .strip method, which removes all space characters (spaces, tabs, newlines, etc..) in front and after a string. Your code should look like this
file = open("Subject.txt", "r")
Subject = file.read().strip()
file.close()

Related

Printing a single line from a file and removing the extra line at the end [duplicate]

This question already has answers here:
How to read a file without newlines?
(12 answers)
Closed last month.
I'm trying to make a script that tells the user where they left off in the game (Ex: The Attic, The Basement, ect.). The problem is that I'm trying to get all of it to print on the same line, but the period at the end of the sentence prints on a different line.
Here is the code
f = open(cd+"/Data/currentGame", "r")
l = open(cd+"/Data/currentLocation", "r")
current_game = f.read()
current_location_lines = l.readlines()
current_location = current_location_lines[0]
f.close()
l.close()
print("You have an existing game where you left off in "+str(current_location)+".")
The problem is that it outputs this:
You have an existing game where you left off in the attic
.
(The period is on a different line.)
It's is because the line you read is always followed by a \n character. You need to remove it. Hence, just replace that last part of your code with this. .strip() will do for you. str(current_location).strip("\n")
Whenever you read a line from a text file, it adds a \n character to tell that new line started from there. You need to remove that while printing or it will mess up with your current statement
Your correct statement is
print("You have an existing game where you left off in "+str(current_location).strip("\n")+".")

How to split one very long line in Pycharm into multiple lines?

After parsing, I've got a lot of urls that have unfortunately joined together in one line. It will take a long time to re-parse, so I ask if there is a method as one long line with Url to turn into a multiple lines - 1 Url per line?
What i have:
'https:// url1.com/bla1','https:// url1.com/bla2',..thousands of urls..,'https:// url999.com/blaN'
What i need:
'https:// url1.com/bla-1',
'https:// url1.com/bla-2',
etc
'https:// url999.com/bla-N'
I've already tried to uncheck Line breaks in Python - Wrapping and Braces and check Ensure right margin is not exceeded - doesn't work
So how can i fix it?
Yes.
First set Code->Style->Wrapping and Braces->Method parameters/Method call arguments to wrap if long or chop down if long.
After that simply call reformat code on the line (Command+Alt+L).
Let's try a simple method, if I understand your query correctly. Read the first file, replace commas with newline character, and write the result to the same file.
urlsfile = open('test1.txt', 'r+') # in case you are getting the data from file itself
urls = urlsfile.readline()
urlsfile.close()
newlines = urls.replace(",", "\n") # otherwise replace newlines with the variable name that you are trying to write to the file
newfile = open('test1.txt','w+')
newfile.write(newlines)
newfile.close()

selection using strings from files

I am trying to make a sort of quiz revision code for my exams. I am however struggling to get the selection for whether the answer is right or not to work. no matter what answer I put it outputs "nope". Each file I use has 6 lines.
import random
file = open("questions.txt", "r")
questions = file.readlines()
file2 = open("answers.txt", "r")
answers = file2.readlines()
question_answering = True
while question_answering:
question = random.randrange(5)
print(questions[question])
answer = input("enter your answer: ")
print(answers[question])
if answer == answers[question]:
print("well done!")
else:
print("nope")
I have included a test which is print(answers[question]) which does output the correct answer that I am looking for but when I input that answer it does not work.
Probably because the answers read from the file still have newlines on them, and your input does not. Strip the newlines off the read answers and it should work.
Newlines (often '\n' or '\r' or a combination thereof, depending on the context) are characters that tell the computer to, well, move to the next line. When you read a file, you often split the lines on the newline character, but whether or not the newline is retained with the line of text is going to be language/library specific. As you can see in the link I included, readLines() retains the newline characters. So you need to remove them to get the answer by itself (without the newline character).
Reading a file without newlines

Removed new line character appears in write to file but not in print to screen

One very stupid thing happens when I modify a string that contained newline characters within it.
After modifying the string variable, I print it. It successfully shows that the new line character has been removed.
When I write the string variable to a file, it prints the new line character there.
I spent hours figuring this out!
import os
import csv
s = "I want this \n new line removed"
s = s.replace("\n", "")
print(s)
file = open('my_file.tsv', 'w')
file.write(s)
file.close()
The above is a sample code. If you run this code, it will run. The string in my real project is a text dynamically fetched from a mysql database -- which is being modified. That contains one or more \n characters within it.
If in the above code, I try replacing that text obtained from the database in a hardcoded manner and running it, it throws me an error saying "EOL while scanning string lateral"
Can you please help me clean this text into something consumable?
Removal of '\r\n' worked!! Thanks a lot #abarnert for the suggestion.
The text wasn't visible to me in code form. It was raw text fetched from db. The raw text just looked like a paragraph with multiple newlines. Hence, I wasn't able to provide real text

How to remove the "\n" from the end of my string [duplicate]

This question already has answers here:
How can I remove a trailing newline?
(27 answers)
Closed 8 years ago.
I had a list that read from a text file into an array but now they all have "\n" on the end. Obviously you dont see it when you print it because it just takes a new line. I want to remove it because it is causing me some hassle.
database = open("database.txt", "r")
databaselist = database.readlines()
thats the code i used to read from the file. I am a total noob so please dont use crazy technical talk otherwise it will go straight over my head
"string with or without newline\n".rstrip('\n')
Using rstrip with \n avoids any unwanted side-effect except that it will remove multiple \n at the end, if present.
Otherwise, you need to use this less elegant function:
def rstrip1(s, c):
return s[:-1] if s[-1]==c else s
Use str.rstrip to remove the newline character at the end of each line:
databaselist = [line.rstrip("\n") for line in database.readlines()]
However, I recommend that you make three more changes to your code to improve efficiency:
Remove the call to readlines. Iterating over a file object yields its lines one at a time.
Remove the "r" argument to open since the function defaults to read-mode. This will not improve the speed of your code, but it will make it less redundant.
Most importantly, use a with-statement to open the file. This will ensure that it is closed automatically when you are done.
In all, the new code will look like this:
with open("database.txt") as database:
databaselist = [line.rstrip("\n") for line in database]

Categories