Python write newline without \n - python

Hey I need to write a string to a text file but i need it to not have a \n as I am using it as a database. The script works fine but doesnt actually write into a newline obviously because I strip()-ed it. I was wondering if there was a way around even in another language.
So far I tried:
textfile = open('pass.txt.','a')
ask = raw_input("[+] Do you want to append you own passwords(y/n)")
if ask == "y":
print "[+] Use quit_appender_now to quit adding string"
while True:
stri = raw_input("[+] Enter word to add-->")
if stri == "quit_appender_now":
break
else:
stri = stri + "\n"
textfile.write(stri.strip())
elif ask =="n":
pass
The reason I dont want to use \n is because of this code:
with open('pass.txt'),'r') as r_text:
for x in r_text:
print repr(x)
The above code will print out the string with \n. Is there any way to get around this?
For example if pass.txt had asdf in there print repr(x) would print asdf\n. I need it to print asdf

As far as I can tell, what you are asking for is impossible because a newline is \n!
To clarify, text files contain sequences of characters. The only way to divide them into lines is to use one or more characters as the end-of-line marker. That's all \n is. (See this answer, suggested by #Daniel's comment, for more details.)
So you can write without newlines, but your file will be one loooong line. If you want to display its contents with repr() but don't like seeing the newline, you'll have to strip it before you print it:
with open('pass.txt'),'r') as r_text:
for x in r_text:
x = x.rstrip("\n") # Don't discard spaces, if any
print repr(x)
If that doesn't solve your problem, then your problem really has no solution and you need to ask a different question about the ultimate purpose of the file you're trying to generate. Someone will point you to a solution other than "writing a newline without writing a newline".

You could make a definition to write a line to a file.
For example:
class Dummy():
def __init__(self):
print('Hello')
self.writeToFile('Writing a line')
self.writeToFile('Writing another line')
def writeToFile(self, value):
self.value = value
# Open file
file = open('DummyFile.txt', 'a')
# Write value to file.
file.write(value)
# Jump to a new line.
file.write('\n')
# close file
file.close()
Dummy()
If you then would read DummyFile.txt, you will not see the \n in the text.

Related

How do I insert empty lines in text output? [duplicate]

I am following a beginners tutorial on Python, there is a small exercise where I have to add an extra function call and print a line between verses, this works fine if I print an empty line in between function calls but if I add an empty print line to the end of my happyBirthday() I get an indent error, without the added print line all works fine though, any suggestions as to why?
Here is the code:
def happyBirthday(person):
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday, dear " + person + ".")
print("Happy Birthday to you!")
print("\n") #error line
happyBirthday('Emily')
happyBirthday('Andre')
happyBirthday('Maria')
You can just do
print()
to get an empty line.
You will always only get an indent error if there is actually an indent error. Double check that your final line is indented the same was as the other lines -- either with spaces or with tabs. Most likely, some of the lines had spaces (or tabs) and the other line had tabs (or spaces).
Trust in the error message -- if it says something specific, assume it to be true and figure out why.
Python 2.x:
Prints a newline
print
Python 3.x:
You must call the function
print()
Source: https://docs.python.org/3.0/whatsnew/3.0.html
Don't do
print("\n")
on the last line. It will give you 2 empty lines.
Python's print function adds a newline character to its input. If you give it no input it will just print a newline character
print()
Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text
my_str = "hello world"
print(my_str + "\n")
If you're doing this a lot, you can also tell print to add 2 newlines instead of just one by changing the end= parameter (by default end="\n")
print("hello world", end="\n\n")
But you probably don't need this last method, the two before are much clearer.
The two common to print a blank line in Python-
The old school way:
print "hello\n"
Writing the word print alone would do that:
print "hello"
print
This is are other ways of printing empty lines in python
# using \n after the string creates an empty line after this string is passed to the the terminal.
print("We need to put about", average_passengers_per_car, "in each car. \n")
print("\n") #prints 2 empty lines
print() #prints 1 empty line

sys.stdin in for loop is not grabbing user input

I have this code (test.py) below:
import sys
for str in sys.stdin.readline():
print ('Got here')
print(str)
For some reason when I run the program python test.py and then I type in abc into my terminal I get this output:
>>abc
THIS IS THE OUTPUT:
Got here
a
Got here
b
Got here
c
Got here
It prints out Got here five times and it also prints out each character a, b, c individually rather than one string like abc. I am doing sys.stdin.readline() to get the entire line but that doesn't seem to work either. Does anyone know what I am doing wrong?
I am new to python and couldn't find this anywhere else on stackoverflow so sorry if this is a obvious question.
readline() reads a single line. Then you iterate over it. Iterating a string gives you the characters, so you are running your loop once for each character in the first line of input.
Use .readlines(), or better, just iterate over the file:
for line in sys.stdin:
But the best way to get interactive input from stdin is to use input() (or raw_input() in Python 2).
You are looping through each character in the string that you got inputted.
import sys
s = sys.stdin.readline()
print ('Got here')
print(s)
# Now I can use string `s` for whatever I want
print(s + "!")
In your original code you got a string from stdin and then you looped through ever character in that input string and printed it out (along with "Got here").
EDIT:
import sys
while True:
s = sys.stdin.readline()
# Now I can do whatever I want with string `s`
print(s + "!")

Hangman in python: have lines be replaced?

I'm working on writing a simple Hangman game in Python from what I know so far (I'm doing Learn Python the Hard Way) and so far I have this:
from sys import argv
import random
script_name, dict_file = argv
hang_list = open(dict_file).read().splitlines()
hang_list = filter(None, hang_list)
word = random.choice(hang_list)
guesses = ''
def compare_words():
global guesses
new_word = ''
for char in word:
if char in guesses:
new_word += char
else:
new_word += "_"
return new_word
def test_letter():
global guesses
letter = raw_input("Guess a letter: ")
guesses += letter
new_word = compare_words()
print "\nCurrent guesses: %s" % guesses
print "%s\n\n" % new_word
if new_word == word:
print "You won!"
else:
test_letter()
test_letter()
I've yet to implement the scoring system (piece of cake) but I have an issue with the layout. As you can tell, this will print "Current guesses: " and the new word each time; however, what I want is four lines that look like:
Guess a letter:
Guesses: abczy
__c__b_
And have those three lines keep updating. However, I am having trouble figuring out how to make the print replace stdout. I believe I need to use the \r escape character, yet I've tried placing that in various places but can't get it to work. So, how should I modify this to get it to replace? I would prefer not to just clear, as then it still makes things a bit messy; I want to just replace what's there. Thanks!
It would be a bit tricky to make this work for all terminals, but if yours understands ANSI escape codes like mine does, this might work:
...
if new_word == word:
print "You won!"
else:
print '\033[F'*7
print ' '*17 + '\b'*17 + '\033[F'
test_letter()
This relies on the ANSI code F: move the cursor up one line; backspaces (\b) alone have no effect once the beginning of the line is reached.
The first print takes you back up to the input line and the second deletes the character that was previously entered.
You can use the escape characters \033c and this will erase the code in a terminal window and put the cursor at the top left.
For example this code:
import time
print("text 1")
time.sleep(1)
print('\033c')
time.sleep(1)
print("text 2")
This code will print "text 1" wait one second, clear the console, wait one second and then print "text 2".
So you could use the code
def test_letter():
print("\033c")
global guesses
letter = raw_input("Guess a letter: ")
guesses += letter
new_word = compare_words()
print "\nCurrent guesses: %s" % guesses
print "%s\n\n" % new_word
if new_word == word:
print "You won!"
else:
test_letter()
What this code will do is clear the console, ask the person to guess a number, display that four line piece of code that you wanted and then clear the console again.
I hope this helps!
If you want to replace the content of a specific line, from a specific position, you can use ANSI Escape Codes. To do this, make sure that you're using stdout.write() rather than print(). You can access this method by using the following import statement:
from sys import stdout
Then, in order to navigate the "cursor" (where text printed with this method will go), use the escape code \u001b[<L>;<C>H (or \u001b[<L>;<C>F where <L> and <C> represent the respective line number and character index of the desired position. For example, if you wanted to set the cursor to line 3; character 2, you would do the following.
stdout.write(u"\u001b[3;2H")
Note the u proceeding the double-quoted string. This is required in Python 2.x, since it contains special characters, but can be omitted in Python 3 and above.
Once you have set the cursor to be at the desired position, anything you write will replace the characters that currently reside there. This is important, because if the replacement string is shorter than the original, you may end up with trailing legacy characters. The simplest way to deal with this is to pad the printing string in spaces.
After doing this you should probably move the cursor back to the end of stdout, using the same method, and flush the output with stdout.flush().
Example
Let's say I had the following output on the terminal:
Name: Shakespeare
Score: 0
Some text...
I could change the score to 1 by running the following:
stdout.write(u"\u001b[2;8H")
stdout.write("1")
stdout.write(u"\u001b[5;0H")
stdout.flush()
Again, the u is optional in Python 3 and up.
Notes
This line-and-character-number method applies to all output currently being displayed in the terminal. This means that if you have anything left from another program or command, for example
$ python game.py
so it is best to clear the output at the start of your program, with something like print(u"\033c"), or os.system("clear"), otherwise you may end up writing to the wrong line.
Also, if your going to use stdout.write() anywhere else, remember to put \n at the end if you want to go to the next line.
The \r character is a carriage return, which means it will return the cursor to the start of the current line. That's OK if you want to redraw the line the cursor is on, but no good if you want to redraw other lines.
To do what you want, you need to use a terminal library like curses on Linux or the console API on Windows. If you are just working on Linux and want a simpler way to access colours, cursor movement and input without echo, you could do worse than try out blessed (https://pypi.python.org/pypi/blessed/).
If you need a cross platform API to do this sort of thing, there is no pure Python way to handle it all yet, but I am working on one. The Screen class in https://github.com/peterbrittain/asciimatics cover all the features above in a cross-platform manner.

Write text to file in columns

As an attorney I am a total newbie in programimg. As an enthusiastic newbie, I learn a lot. (what are variables, ect.) ).
So I'm working a lot with dir() and I'm looking into results. It would by nicer if I could see the output in one or more columns. So I want to write my first program which write for example dir(sys) in a output file in columns.
So far I've got this:
textfile = open('output.txt','w')
syslist = dir(sys)
for x in syslist:
print(x)
The output on display is exactly what I want, but when I use the .write like:
textfile = open('output.txt','w')
syslist = dir(sys)
for x in syslist:
textfile.write(x)
textfile.close()
The text is in lines.
Can anyone pleaase help me, how to write the output of dir(sys) to a file in columns?
If I can ask you, please write the easysiet way, because I really have to look almost after for every word you write in documentation. Thanks in advance.
print adds a newline after the string printed by default, file.write doesn't. You can do:
for x in syslist: textfile.write("%s\n" % x)
...to add newlines as you're appending. Or:
for x in syslist: textfile.write("%s\t" % x)
...for tabs in between.
I hope this is clear for you "prima facie" ;)
The other answers seem to be correct if they guess that you're trying to add newlines that .write doesn't provide. But since you're new to programming, I'll point out some good practices in python that end up making your life easier:
with open('output.txt', 'w') as textfile:
for x in dir(sys):
textfile.write('{f}\n'.format(f=x))
The 'with' uses 'open' as a context manager. It automatically closes the file it opens, and allows you to see at a quick glance where the file is open. Only keep things inside the context manager that need to be there. Also, using .format is often encouraged.
Welcome to Python!
The following code will give you a tab-separated list in three columns, but it won't justify the output for you. It's not fully optimized so it should be easier to understand, and I've commented the portions that were added.
textfile = open('output.txt','w')
syslist = dir(sys)
MAX_COLUMNS = 3 # Maximum number of columns to print
colcount = 0 # Track the column number
for x in syslist:
# First thing we do is add one to the column count when
# starting the loop. Since we're doing some math on it below
# we want to make sure we don't divide by zero.
colcount += 1
textfile.write(x)
# After each entry, add a tab character ("\t")
textfile.write("\t")
# Now, check the column count against the MAX_COLUMNS. We
# use a modulus operator (%) to get the remainder after dividing;
# any number divisible by 3 in our example will return '0'
# via modulus.
if colcount % MAX_COLUMNS == 0:
# Now write out a new-line ("\n") to move to the next line.
textfile.write("\n")
textfile.close()
Hope that helps!
I'm a little confused by your question, but I imagine the answer is as simple as adding in tabs. So change textfile.write(x) to textfile.write(x + "\t"), no? You can adjust the number of tabs based on the size of the data.
I'm editing my answer.
Note that dir(sys) gives you an array of string values. These string values do not have any formatting. The print x command adds a newline character by default, which is why you are seeing them each on their own line. However, write does not. So when you call write, you need to add in any necessary formatting. If you want it to look identical to the output of print, you need to add in write(x + "\n") to get those newline characters that print was automatically including.

Strings won't compare properly

I'm new to python so excuse any poor code you may find
The problem I'm having is that I'm trying to compare two strings, one from a file and one from user input, to see if they match. However, when comparing what seem to me identical strings, the if statement returns false. I have used the str() function to turn both of the values into strings, but it still doesn't want to play ball.
For reference, the line of the file is two strings, separated by a comma, and the 'question' part is before the comma and the 'answer' after it. At present, both the strings are test strings, and so have the values of 'Question' and 'Answer'
import linecache
def askQuestion(question, answer):
choice = input(question)
str(choice)
if choice == answer:
print("Correct")
else:
print("Bad luck")
file = "C://questions.txt"
text = linecache.getline(file, 1)
question = text.split(",", 1)[0]
answer = text.split(",", 1)[-1]
str(answer)
askQuestion(question, answer)
I am typing in exactly what the file has i.e. capital letters in the right place, for note.
I'm sure the answer obvious, but I'm at a loss, so any help would be kindly appreciated.
Thanks!
text = linecache.getline(file, 1)
question = text.split(",", 1)[0]
answer = text.split(",", 1)[-1]
this is more commonly written
text = linecache.getline(file, 1)
question, answer = text.split(",", 1)
The results will be a string. There is no interpretation happening. Also, you need to store the result of str().
my_string = str(number)
By calling str() but not saving it the result is being lost. Not important here, but something to keep in mind.
As Alex mentions in the comment above you are missing the call to strip to remove the newline. How do I know? I tried it in the interpreter.
$ python
>>> import linecache
>>> line = linecache.getline("tmpfile", 1)
>>> line
'* Contact Numbers\n'
See that '\n' there? That is your problem.
Another way would have been to invoke pdb the Python Debugger. Just add
import pdb; pdb.set_trace()
where you want to stop the execution of a Python script.
Good luck.

Categories

Resources