I am reading files in a folder in a python. I want print the each file content separate by a single empty line.
So, after the for loop I am adding print("\n") which adding two empty lines of each file content. How can I resolve this problem?
print()
will print a single new line in Python 3 (no parens needed in Python 2).
The docs for print() describe this behavior (notice the end parameter), and this question discusses disabling it.
Because print automatically adds a new line, you don't have to do that manually, just call it with an empty string:
print("")
From help(print) (I think you're using Python 3):
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
So print()'s default end argument is \n. That means you don't need add a \n like print('\n'). This will print two newlines, just use print().
By the way, if you're using Python 2, use print.
print has a \n embedded in it....so you don't need to add \n by yourself
Or, if you want to be really explicit, use
sys.stdout.write('\n')
Write method doesn't append line break by default. It's probably a bit more intuitive than an empty print.
Related
I'm going back through Python Crash Course 2nd Edition for about the third time to cement my knowledge, & I've run into something interesting that I haven't actually accounted for in previous runs. When printing a lists length with the len() function, I realized I am not exactly sure how to perform this on a new line in this situation, so I added a separate print function above it that begins a new line itself. This causes the next line to be pushed down yet another line, as I'm assuming the line that is supposed to have my length on it, doesn't want to take its place where the previous print function already is, making 2 spacer lines. Is there a specific way I can print the length of this list on a new line without utilizing a separate print function?
I apologize if this seems silly. My code is as follows:
# -- Temporarily sort a list in alphabetical order -- #
colleges = ['Suffolk', 'Westbury', 'Maritime']
print("\nHere is the original list:")
print(*colleges, sep=', ')
print("\nHere is the temporarily sorted list:")
print(*sorted(colleges), sep=', ')
print("\nHere is the original list again:")
print(*colleges, sep=', ')
# -- Sorts list in reverse order, not alphabetically -- #
print("\nHere is a reversed list, not in alphabetical order:")
colleges.reverse()
print(*colleges, sep=', ')
# -- Printing the length of the list -- #
print("\n")
print(len(colleges))
I appreciate any help! These fundamentals are important to me.
The print() function automatically ends with a newline character (\n).
Then
print("\n")
print(len(colleges))
Equals
\n\nlen(colleges)\n
To achieve what you need you can make use of the extra arguments of print(). Like so:
print('\n', len(colleges))
Is there a specific way I can print the length of this list on a new line without utilizing a separate print function?
Omitting the print function preceding print(len(colleges)) will do the job.
The preceding print("\n") will print a new line, and end with a newline, hence the 2-line spacer.
See https://docs.python.org/3/library/functions.html#print - all print statements end with a newline by default.
You don't need the \n function. The len function automatically does this for you.
The reason why it does this is because all print statements automatically does this anyway.
Here is one solution:
# -- Printing the length of the list -- #
str = "\n" + str(len(colleges))
print(str)
Here is another:
# -- Printing the length of the list -- #
print()
print(len(colleges))
In general, any solution will involve changing this line somehow because it will always print two lines:
print("\n")
I don't know how it works and can't see answer for this. I wanted to replace comma to dot in file. So i write this code:
with fileinput.FileInput("tabela.txt", inplace=True, backup='.bak') as file:
for line in file:
line = line.replace(',', '.')
and i thought it should work. But it didn't. But when i replace line=line.replace(...) to:
print(line.replace(",", "."), end='')
it works fine. Can someone explain why line=line.replace(...) doesn't work but print(...) which should just print something (and it even doesn't print lines) replace my comma to dots?
Thanks for answers
EDIT: I said that print should just print something, but ofc it's not true (i think) because as I can see it replace strings in my file in some reason with replace function.
From the docs
Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently).
So the library is built with the use-case of "get input in a variable and output to standard out" in mind. Hence, print is the intended mechanism.
Simply assigning to a local variable and then discarding the result does nothing. It replaces the string in memory and then... garbage collects it soon after. The real-world analogy would be doing a bunch of math homework on a sheet of paper and then putting the paper in the trash rather than submitting it; my teacher isn't going to grade what I throw away.
It appears that Python's io.StringIO adds an extra newline at the end when I'm calling its getvalue method.
For the following code:
import io
s = io.StringIO()
s.write("1\n2\n3\n4\n5\n")
res = s.getvalue()
s.close()
print(res)
What I'm getting is this, with an extra newline in the end:
1
2
3
4
5
I checked the output with a hex editor, and I'm sure there's an extra newline.
The document says that:
The newline argument works like that of TextIOWrapper. The default is to consider only \n characters as ends of lines and to do no newline translation. If newline is set to None, newlines are written as \n on all platforms, but universal newline decoding is still performed when reading.
And I don't recall the write method append newlines per call.
So why is it adding newlines? I'm writing a script so I would like to make sure that it's behavior is consistent.
StringIO isn't doing this, it's print.
print prints all its arguments, seperated by sep (by default a space), and ending with end, by default a newline. You can suppress that by doing:
print(res, end="")
I have a file which currently stores a string eeb39d3e-dd4f-11e8-acf7-a6389e8e7978
which I am trying to pass into as a variable to my subprocess command.
My current code looks like this
with open(logfilnavn, 'r') as t:
test = t.readlines()
print(test)
But this prints ['eeb39d3e-dd4f-11e8-acf7-a6389e8e7978\n'] and I don't want the part with ['\n'] to be passed into my command, so i'm trying to remove them by using replace.
with open(logfilnavn, 'r') as t:
test = t.readlines()
removestrings = test.replace('[', '').replace('[', '').replace('\\', '').replace("'", '').replace('n', '')
print(removestrings)
I get an exception value saying this so how can I replace these with nothing and store them as a string for my subprocess command?
'list' object has no attribute 'replace'
so how can I replace these with nothing and store them as a string for my subprocess command?
readline() returns a list. Try print(test[0].strip())
You can read the whole file and split lines using str.splitlines:
test = t.read().splitlines()
Your test variable is a list, because readlines() returns a list of all lines read.
Since you said the file only contains this one line, you probably wish to perform the replace on only the first line that you read:
removestrings = test[0].replace('[', '').replace('[', '').replace('\\', '').replace("'", '').replace('n', '')
Where you went wrong...
file.readlines() in python returns an array (collection or grouping of the same variable type) of the lines in the file -- arrays in python are called lists. you, here are treating the list as a string. you must first target the string inside it, then apply that string-only function.
In this case however, this would not work as you are trying to change the way the python interpretter has displayed it for one to understand.
Further information...
In code it would not be a string - we just can't easily understand the stack, heap and memory addresses easily. The example below would work for any number of lines (but it will only print the first element) you will need to change that and
this may be useful...
you could perhaps make the variables globally available (so that other parts of the program can read them
more useless stuff
before they go out of scope - the word used to mean the points at which the interpreter (what runs the program) believes the variable is useful - so that it can remove it from memory, or in much larger programs only worry about the locality of variables e.g. when using for loops i is used a lot without scope there would need to be a different name for each variable in the whole project. scopes however get specialised (meaning that if a scope contains the re-declaration of a variable this would fail as it is already seen as being one. an easy way to understand this might be to think of them being branches and the connections between the tips of branches. they don't touch along with their variables.
solution?
e.g:
with open(logfilenavn, 'r') as file:
lines = file.readlines() # creates a list
# an in-line for loop that goes through each item and takes off the last character: \n - the newline character
#this will work with any number of lines
strippedLines = [line[:-1] for line in lines]
#or
strippedLines = [line.replace('\n', '') for line in lines]
#you can now print the string stored within the list
print(strippedLines[0]) # this prints the first element in the list
I hope this helped!
You get the error because readlines returns a list object. Since you mentioned in the comment that there is just one line in the file, its better to use readline() instead,
line = "" # so you can use it as a variable outside `with` scope,
with open("logfilnavn", 'r') as t:
line = t.readline()
print(line)
# output,
eeb39d3e-dd4f-11e8-acf7-a6389e8e7978
readlines will return a list of lines, and you can't use replace with a list.
If you really want to use readlines, you should know that it doesn't remove the newline character from the end, you'll have to do it yourself.
lines = [line.rstrip('\n') for line in t.readlines()]
But still, after removing the newline character yourself from the end of each line, you'll have a list of lines. And from the question, it looks like, you only have one line, you can just access first line lines[0].
Or you can just leave out readlines, and just use read, it'll read all of the contents from the file. And then just do rstrip.
contents = t.read().rstrip('\n')
In Python when I do
print "Line 1 is"
print "big"
The output I get is
Line 1 is
big
Where does the newline come from? And how do I type both statements in the same line using two print statements?
print adds a newline by default. To avoid this, use a trailing ,:
print "Line 1 is",
print "big"
The , will still yield a space. To avoid the space as well, either concatenate your strings and use a single print statement, or use sys.stdout.write() instead.
From the documentation:
A '\n' character is written at the
end, unless the print statement ends
with a comma. This is the only action
if the statement contains just the
keyword print.
If you need full control of the bytes written to the output, you might want to use sys.stdout
import sys
sys.stdout.write("Line 1 is ")
sys.stdout.write("big!\n")
When not outputing a newline (\n) you will need to explicitly call flush, for your data to not be buffered, like so:
sys.stdout.flush()
this is standard functionality, use print "foo",