I want to open a file and read each line using f.seek() and f.tell():
test.txt:
abc
def
ghi
jkl
My code is:
f = open('test.txt', 'r')
last_pos = f.tell() # get to know the current position in the file
last_pos = last_pos + 1
f.seek(last_pos) # to change the current position in a file
text= f.readlines(last_pos)
print text
It reads the whole file.
ok, you may use this:
f = open( ... )
f.seek(last_pos)
line = f.readline() # no 's' at the end of `readline()`
last_pos = f.tell()
f.close()
just remember, last_pos is not a line number in your file, it's a byte offset from the beginning of the file -- there's no point in incrementing/decrementing it.
Is there any reason why you have to use f.tell and f.seek? The file object in Python is iterable - meaning that you can loop over a file's lines natively without having to worry about much else:
with open('test.txt','r') as file:
for line in file:
#work with line
A way for getting current position When you want to change a specific line of a file:
cp = 0 # current position
with open("my_file") as infile:
while True:
ret = next(infile)
cp += ret.__len__()
if ret == string_value:
break
print(">> Current position: ", cp)
Skipping lines using islice works perfectly for me and looks like is closer to what you're looking for (jumping to a specific line in the file):
from itertools import islice
with open('test.txt','r') as f:
f = islice(f, last_pos, None)
for line in f:
#work with line
Where last_pos is the line you stopped reading the last time. It will start the iteration one line after last_pos.
Related
So,I have this problem,the code below will delete the 3rd line in a text file.
with open("sample.txt","r") as f:
lines = f.readlines()
del lines[2]
with open("sample.txt", "w+") as f2:
for line in lines:
f2.write(line)
How to delete all lines from a text file?
Why use loop if you want to have an empty file anyways?
f = open("sample.txt", "r+")
f.seek(0)
f.truncate()
This will empty the content without deleting the file!
I think you to need something like this
import os
def delete_line(original_file, line_number):
""" Delete a line from a file at the given line number """
is_skipped = False
current_index = 1
dummy_file = original_file + '.bak'
# Open original file in read only mode and dummy file in write mode
with open(original_file, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
# Line by line copy data from original file to dummy file
for line in read_obj:
# If current line number matches the given line number then skip copying
if current_index != line_number:
write_obj.write(line)
else:
is_skipped = True
current_index += 1
# If any line is skipped then rename dummy file as original file
if is_skipped:
os.remove(original_file)
os.rename(dummy_file, original_file)
else:
os.remove(dummy_file)
How to fetch the second line data from text file in Python.
I have a text file and in file there are some data in line by line_
Dog
Cat
Cow
How to fetch the second line which is “Cat” and store in a variable in python
var = # “Cat”
You should place the text file in the same directory with your Python code, which could be the following:
with open("animals.txt", "r") as f:
animals = [line.strip() for line in f]
second_line = animals[1]
Now, the variable "second_line" contains the data you want.
You can open a file, then read line by line while counting the line number as follows:
if __name__ == '__main__':
input_path = "data/animals.txt"
var = None
with open(input_path, "r") as fin:
n_lines = 0
for line in fin:
n_lines += 1
if 2 == n_lines:
var = line.strip()
break
print(var)
Result:
Cat
If the file is big, you may avoid reading all file and use readline to read one line twice:
with open ('file.txt') as file:
line = file.readline()
line = file.readline()
print(line)
...or check 'seek' method to start reading at specific character index.
I am trying to insert a file and I keep getting a syntax error on the line line = infile.redline()
def main():
# Declare variables
line = ''
counter = 0
# Prompt for file name
fileName = input('Enter the name of the file: ')
# Open the specified file for reading
infile = open('test.txt', 'r')
# Priming read
line = infile.redline()
counter = 1
# Read in and display first five lines
while line != '' and counter <= 5:
# Strip '\n'
line = line.rtrip('\n')
print(line)
1ine = infile.readline()
# Update counter when line is read
counter +=1
# Close file
infile.close()
# Call the main function.
main()
rtrip should be rstrip. redline should be readline. infile.close() should be indented, and main() should not be.
However, the most serious problem is here:
1ine = infile.readline()
That first character is a one, not an L.
Knowing the standard libraries can make your life much simpler!
from itertools import islice
def main():
fname = input('Enter the name of the file: ')
with open(fname) as inf:
for line in islice(inf, 5): # get the first 5 lines
print(line.rstrip())
if __name__=="__main__":
main()
It is not redline but readline:
line = infile.redline()
I'm trying to add specific lines to a specific area in my file.
I am using this:
new_file = open("file.txt", "r+")
for line in new_file:
if line == "; Include below":
line = line + "\nIncluded text"
new_file.write(line)
else:
new_file.write(line)
But for some reason the content of my file.txt is duplicating.
Edit: If my file looks like:
blablablablablablabal
balablablabalablablbla
include below
blablablablablabalablab
ablablablabalbalablaba
I want make it look like:
blablablablablablabal
balablablabalablablbla
include below
included text
blablablablablabalablab
ablablablabalbalablaba
You cannot safely write to a file while reading, it is better to read the file into memory, update it, and rewrite it to file.
with open("file.txt", "r") as in_file:
buf = in_file.readlines()
with open("file.txt", "w") as out_file:
for line in buf:
if line == "; Include this text\n":
line = line + "Include below\n"
out_file.write(line)
This is what I did.
def find_append_to_file(filename, find, insert):
"""Find and append text in a file."""
with open(filename, 'r+') as file:
lines = file.read()
index = repr(lines).find(find) - 1
if index < 0:
raise ValueError("The text was not found in the file!")
len_found = len(find) - 1
old_lines = lines[index + len_found:]
file.seek(index)
file.write(insert)
file.write(old_lines)
# end find_append_to_file
Use sed:
$ sed '/^include below/aincluded text' < file.txt
Explanation:
/^include below/: matches every line that starts (^) with include below
a: appends a newline and the following text
includeed text: the text that a appends
Edit: Using Python:
for line in open("file.txt").readlines():
print(line, end="")
if line.startswith("include below"):
print("included text")
I am trying to replace text in a text file by reading each line, testing it, then writing if it needs to be updated. I DO NOT want to save as a new file, as my script already backs up the files first and operates on the backups.
Here is what I have so far... I get fpath from os.walk() and I guarantee that the pathmatch var returns correctly:
fpath = os.path.join(thisdir, filename)
with open(fpath, 'r+') as f:
for line in f.readlines():
if '<a href="' in line:
for test in filelist:
pathmatch = file_match(line, test)
if pathmatch is not None:
repstring = filelist[test] + pathmatch
print 'old line:', line
line = line.replace(test, repstring)
print 'new line:', line
f.write(line)
But what ends up happening is that I only get a few lines (updated correctly, mind you, but repeated from earlier in the file) corrected. I think this is a scoping issue, afaict.
*Also: I would like to know how to only replace the text upon the first instance of the match, for ex., I don't want to match the display text, only the underlying href.
First, you want to write the line whether it matches the pattern or not. Otherwise, you're writing out only the matched lines.
Second, between reading the lines and writing the results, you'll need to either truncate the file (can f.seek(0) then f.truncate()), or close the original and reopen. Picking the former, I'd end up with something like:
fpath = os.path.join(thisdir, filename)
with open(fpath, 'r+') as f:
lines = f.readlines()
f.seek(0)
f.truncate()
for line in lines:
if '<a href="' in line:
for test in filelist:
pathmatch = file_match(line, test)
if pathmatch is not None:
repstring = filelist[test] + pathmatch
line = line.replace(test, repstring)
f.write(line)
Open the file for read and copy all of the lines into memory. Close the file.
Apply your transformations on the lines in memory.
Open the file for write and write out all the lines of text in memory.
with open(filename, "r") as f:
lines = (line.rstrip() for line in f)
altered_lines = [some_func(line) if regex.match(line) else line for line in lines]
with open(filename, "w") as f:
f.write('\n'.join(altered_lines) + '\n')
A (relatively) safe way to replace a line in a file.
#!/usr/bin/python
# defensive programming style
# function to replace a line in a file
# and not destroy data in case of error
def replace_line(filepath, oldline, newline ):
"""
replace a line in a temporary file,
then copy it over into the
original file if everything goes well
"""
# quick parameter checks
assert os.exists(filepath) # !
assert ( oldline and str(oldline) ) # is not empty and is a string
assert ( newline and str(newline) )
replaced = False
written = False
try:
with open(filepath, 'r+') as f: # open for read/write -- alias to f
lines = f.readlines() # get all lines in file
if oldline not in lines:
pass # line not found in file, do nothing
else:
tmpfile = NamedTemporaryFile(delete=True) # temp file opened for writing
for line in lines: # process each line
if line == oldline: # find the line we want
tmpfile.write(newline) # replace it
replaced = True
else:
tmpfile.write(oldline) # write old line unchanged
if replaced: # overwrite the original file
f.seek(0) # beginning of file
f.truncate() # empties out original file
for tmplines in tmpfile:
f.write(tmplines) # writes each line to original file
written = True
tmpfile.close() # tmpfile auto deleted
f.close() # we opened it , we close it
except IOError, ioe: # if something bad happened.
printf ("ERROR" , ioe)
f.close()
return False
return replaced and written # replacement happened with no errors = True
(note: this replaces entire lines only , and all of the lines that match in the file)