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.
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 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
I want to insert a line into file "original.txt" (the file contains about 200 lines). the line neds to be inserted two lines after a string is found in one of the existing lines. This is my code, I am using a couple of print options that show me that the line is being added to the list, in the spot I need, but the file "original.txt" is not being edited
with open("original.txt", "r+") as file:
lines = file.readlines() # makes file into a list of lines
print(lines) #test
for number, item in enumerate(lines):
if testStr in item:
i = number +2
print(i) #test
lines.insert(i, newLine)
print(lines) #test
break
file.close()
I am turning the lines in the text into a list, then I enumerate the lines as I look for the string, assigning the value of the line to i and adding 2 so that the new line is inserted two lines after, the print() fiction shows the line was added in the correct spot, but the text "original.txt" is not modified
You seem to misunderstand what your code is doing. Lets go line by line
with open("original.txt", "r+") as file: # open a file for reading
lines = file.readlines() # read the contents into a list of lines
print(lines) # print the whole file
for number, item in enumerate(lines): # iterate over lines
if testStr in item:
i = number +2
print(i) #test
lines.insert(i, newLine) # insert lines into the list
print(lines) #test
break # get out of the look
file.close() # not needed, with statement takes care of closing
You are not modifying the file. You read the file into a list of strings and modify the list. To modify the actual file you need to open it for writing and write the list back into it. Something like this at the end of the code might work
with open("modified.txt", "w") as f:
for line in lines: f.write(line)
You never modified the original text. Your codes reads the lines into local memory, one at a time. When you identify your trigger, you count two lines, and then insert the undefined value newLine into your local copy. At no point in your code did you modify the original file.
One way is to close the file and then rewrite it from your final value of lines. Do not modify the file while you're reading it -- it's good that you read it all in and then start processing.
Another way is to write to a new file as you go, then use a system command to replace the original file with your new version.
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