This question already has answers here:
Python program prints an extra empty line when reading a text file
(4 answers)
Closed 3 years ago.
I'm trying to read a file into a list using Python. But when I do that the list appears with blank lines after each entry. The source file doesn't have that!
My code:
aws_env_list="../../../source_files/aws_environments/aws_environments_all.txt"
with open(aws_env_list, 'r') as aws_envs:
for line in aws_envs:
print(line)
Each line prints out with a blank line after each entry:
company-lab
company-bill
company-stage
company-dlab
company-nonprod
company-prod
company-eng-cis
The source file looks like this:
company-lab
company-bill
company-stage
company-dlab
company-nonprod
company-prod
company-eng-cis
How do I get rid of the blank line after each entry?
When you iterate over a file line-by-line using:
for line in aws_envs:
The value of line includes the end-of-line character...and the print command, by default, adds an end-of-line character to your output. You can suppress that by setting the end parameter to an empty value. Compare:
>>> print('one');print('two')
one
two
Vs:
>>> print('one', end='');print('two')
onetwo
Your file has a new line character at the end of each line like:
company-lab\n
company-bill\n
company-stage\n
company-dlab\n
company-nonprod\n
company-prod\n
company-eng-cis # not here though this has an EOF (end-of-file) character.
So your call to print(line) is including these in the print! You can avoid this like:
aws_env_list="../../../source_files/aws_environments/aws_environments_all.txt"
with open(aws_env_list, 'r') as aws_envs:
for line in aws_envs.readlines():
print(line.strip()) # just strip the \n away!
UPDATE
If you would like to compute with just the text and not the newline character you can strip it away like this:
aws_env_list="../../../source_files/aws_environments/aws_environments_all.txt"
with open(aws_env_list, 'r') as aws_envs:
for line in aws_envs.readlines():
line = line.strip() # You can strip it here and reassign it to the same variable
# Now all your previous code with the variable 'line' will work as expected
print(line) # no need to strip again
do_computations(line) # you can pass it to functions without worry
Related
I am a beginner in Python and been playing around with what I know so far and came across the below problem. Can someone kindly help me out to understand why this occurs?
suppose I have a text named 'test.txt' file that contains the following,
This is the first line
This is the second line
This is the third line
I print every line in this text file by doing as below,
with open('test.txt', 'r') as f:
for line in f:
print(line)
However though, the output we get is,
This is the first line
This is the second line
This is the third line
As shown above we get an empty line printed due to each line in the text file containing a '\n' at the end of the each line.
To get rid of the empty line that is printed above, I know we could do something like,
with open('test.txt', 'r') as f:
for line in f:
print(line, end='')
This gives us the following output,
This is the first line
This is the second line
This is the third line
What I do not understand is, how have we been able to get rid of the newline character just by adding an empty string to the end of each line?
Note that '\n' is the default parameter given to end.
This is from the official python docs:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False).
You can check the docs here: https://docs.python.org/3/library/functions.html#print
The print function in python has a default value of \n for the parameter end, when you override that value by empty string '' => print(line, end='') you remove the new line behavior.
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.
In order to extract some values from this file :
I need to read it line by line.
I tried to read line by line first but i don't know why it doesn't work.
I tried this :
#! /usr/bin/python
file = open('/home/results/err.txt')
for line in file.readline():
print line
EDIT:
Problem: working but not showing this lines (this is the file)
Just the last line of them which is: (this is what is generated)
You need to iterate through the file rather than the line:
#! /usr/bin/python
file = open('/home/results/err.txt')
for line in file:
print line
file.readline() only reads the first line. When you iterate over it, you are iterating over the characters in the line.
file.readline() already reads one line. Iterating over that line gives you the individual characters.
Instead, use:
for line in file:
…
Try this :
#! /usr/bin/python
file = open('/home/results/err.txt')
for line in file.readlines():
print line
You might want to use a context manager with that to automatically close your opened file after the lines have been read, that is to ensure nothing unexpected happens to your file while python is processing it.
with open('/home/results/err.txt', 'r') as file:
for line in file:
print line
readline() would read your file line-by-line but iterating over that would print the letters individually.
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.
I have a piece of code that's removing some unwanted lines from a text file and writing the results to a new one:
f = open('messyParamsList.txt')
g = open('cleanerParamsList.txt','w')
for line in f:
if not line.startswith('W'):
g.write('%s\n' % line)
The original file is single-spaced, but the new file has an empty line between each line of text. How can I lose the empty lines?
You're not removing the newline from the input lines, so you shouldn't be adding one (\n) on output.
Either strip the newlines off the lines you read or don't add new ones as you write it out.
Just do:
f = open('messyParamsList.txt')
g = open('cleanerParamsList.txt','w')
for line in f:
if not line.startswith('W'):
g.write(line)
Every line that you read from original file has \n (new line) character at the end, so do not add another one (right now you are adding one, which means you actually introduce empty lines).
My guess is that the variable "line" already has a newline in it, but you're writing an additional newline with the g.write('%s*\n*' % line)
line has a newline at the end.
Remove the \n from your write, or rstrip line.