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.
Related
This question already has answers here:
Prepend line to beginning of a file
(11 answers)
Closed 1 year ago.
I have build a code that does the following:
#code is supposed to access servers about 20 of them
#server details are in 'CheckFolders.ini'
# retrieve size, file numbers and number of folders information
# put all that in a file CheckFoldersResult.txt
Need to find out how can i write to CheckFoldersResult.txt so that the latest results are appended starting from the beginning of the file instead of appending at end of the existing text.
I'd read the results, insert the lines I want at the top, then overwrite the file like so:
def update_file(filepath, new_lines):
lines = []
with open(filepath, 'r') as f:
lines = f.readlines()
rev_lines = reversed(new_lines)
for line in rev_lines:
lines.insert(0, line)
with open(filepath, 'w') as f:
f.writelines(lines)
This question already has answers here:
Why can't I call read() twice on an open file?
(7 answers)
Closed 2 years ago.
This should be basic but I can't find a quick response to my question, sorry if this is a double.
I am writing a small code to learn how to manipulate files and count the number of lines, words and of character inside a txt file.
Could you please explain why in the code below if I don't reload for the second time the file using another with open(), the code fails to count the len(f.read) properly? Without it, it returns 0.
Comments to improve the code are welcomed.
def wc(nomFichier):
nb_car=0
nb_words=0
nb_lig=0
with open(nomFichier) as f:
for line in f:
words = line.split()
nb_words += len(words)
nb_lig +=1
with open(nomFichier) as f: #Why I need to reload the file?
nb_car=len(f.read()) #f.read().stripignore to ignore ligne\n
f.close()
return (nb_car, nb_words, nb_lig)
You don't need to reopen the file.
def word_count(file_path):
count_chars=0
count_words=0
count_lines=0
with open(file_path) as f:
for line in f:
count_chars += len(line)
count_words += len(line.split())
count_lines +=1
return (count_chars, count_words, count_lines)
Note that I changed the variable names to one I think are more appropriate.
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:
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.
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