I want to write a program that gives some integer value. I have a file with a value in the first line. How can I change the value of line (for example to 12). This is my code, but
this gets a value and I want to go to line 2 and addition m to that number in line 2 but it doesn't work.
t=open('pash.txt', 'r')
g=[]
for i in range(3):
g.append(t.readline())
t.close()
g[o-1]=(int(g[o-1]))+m # o is the number of line in file
print(g[o-1])
t=open("pash.txt","w")
for i in range(3):
t.write(str(g[i]))
t.write('\n')
t.close()
You can open, read file line by line using readlines, modify content and re-write the file:
with open('pash.txt', 'r') as f:
lines = f.readlines()
m = 5 # value you need to add to a line.
o = 2 # line number of the line to modify.
with open('pash.txt', 'w') as f:
for x, line in enumerate(lines):
if x == o:
line = int(line) + m
f.write(line)
Related
f=open('file.txt', 'a',
encoding='utf-8')
f.write('+1/n')
f.write('+2/n')
f.close()
In file.txt, the result is
Line 1
Line 2
+1
+2
I want this to be
Line 1+1
Line 2+2
How can I write a text at the end of each sentence?
You can open the file and read in the lines with readlines(). Then seek back to the beginning and write the lines with you addition. Something like:
with open(path,'r+') as f:
lines = f.readlines()
f.seek(0)
for i, line in enumerate(map(str.strip, lines)):
f.write(f'{line}+{i+1}\n')
Try this one:
with open('file.txt','r', encoding='utf-8') as fr:
lines = fr.readlines()
with open('file.txt','w', encoding='utf-8') as fw:
for i,l in enumerate(lines):
fw.write(f"l+{i+1}\n")
Original text file:
line 1
line 2
line 3
line 4
Code:
with open("file.txt", "r") as f:
lines = f.readlines()
with open("file.txt", "w") as out_f:
for i, j in enumerate(lines): # i represents the index of the line starting at 0. j represents the line itself
out_f.write(j.strip("\n") + f"+{i + 1}\n")
File after output:
line 1+1
line 2+2
line 3+3
line 4+4
Suppose I have a text file that goes like this:
AAAAAAAAAAAAAAAAAAAAA #<--- line 1
BBBBBBBBBBBBBBBBBBBBB #<--- line 2
CCCCCCCCCCCCCCCCCCCCC #<--- line 3
DDDDDDDDDDDDDDDDDDDDD #<--- line 4
EEEEEEEEEEEEEEEEEEEEE #<--- line 5
FFFFFFFFFFFFFFFFFFFFF #<--- line 6
GGGGGGGGGGGGGGGGGGGGG #<--- line 7
HHHHHHHHHHHHHHHHHHHHH #<--- line 8
Ignore "#<--- line...", it's just for demonstration
Assumptions
I don't know what line 3 is going to contain (because it changes
all the time)...
The first 2 lines have to be deleted...
After the first 2 lines, I want to keep 3 lines...
Then, I want to delete all lines after the 3rd line.
End Result
The end result should look like this:
CCCCCCCCCCCCCCCCCCCCC #<--- line 3
DDDDDDDDDDDDDDDDDDDDD #<--- line 4
EEEEEEEEEEEEEEEEEEEEE #<--- line 5
Lines deleted: First 2 + Everything after the next 3 (i.e. after line 5)
Required
All Pythonic suggestions are welcome! Thanks!
Reference Material
https://thispointer.com/python-how-to-delete-specific-lines-in-a-file-in-a-memory-efficient-way/
def delete_multiple_lines(original_file, line_numbers):
"""In a file, delete the lines at line number in given list"""
is_skipped = False
counter = 0
# Create name of dummy / temporary file
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 exist in list then skip copying that line
if counter not in line_numbers:
write_obj.write(line)
else:
is_skipped = True
counter += 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)
Then...
delete_multiple_lines('sample.txt', [0,1,2])
The problem with this method might be that, if your file had 1-100 lines on top to delete, you'll have to specify [0,1,2...100]. Right?
Answer
Courtesy of #sandes
The following code will:
delete the first 63
get you the next 95
ignore the rest
create a new file
with open("sample.txt", "r") as f:
lines = f.readlines()
new_lines = []
idx_lines_wanted = [x for x in range(63,((63*2)+95))]
# delete first 63, then get the next 95
for i, line in enumerate(lines):
if i > len(idx_lines_wanted) -1:
break
if i in idx_lines_wanted:
new_lines.append(line)
with open("sample2.txt", "w") as f:
for line in new_lines:
f.write(line)
EDIT: iterating directly over f
based in #Kenny's comment and #chepner's suggestion
with open("your_file.txt", "r") as f:
new_lines = []
for idx, line in enumerate(f):
if idx in [x for x in range(2,5)]: #[2,3,4]
new_lines.append(line)
with open("your_new_file.txt", "w") as f:
for line in new_lines:
f.write(line)
This is really something that's better handled by an actual text editor.
import subprocess
subprocess.run(['ed', original_file], input=b'1,2d\n+3,$d\nwq\n')
A crash course in ed, the POSIX standard text editor.
ed opens the file named by its argument. It then proceeds to read commands from its standard input. Each command is a single character, with some commands taking one or two "addresses" to indicate which lines to operate on.
After each command, the "current" line number is set to the line last affected by a command. This is used with relative addresses, as we'll see in a moment.
1,2d means to delete lines 1 through 2; the current line is set to 2
+3,$d deletes all the lines from line 5 (current line is 2, so 2 + 3 == 5) through the end of the file ($ is a special address indicating the last line of the file)
wq writes all changes to disk and quits the editor.
I have a file, after reading a line from the file I have named it current_line, I want to fetch the 4th line above the current_line. How can this be done using python?
line 1
line 2
line 3
line 4
line 5
line 6
Now say I have fetched line 6 and I have made
current_line = line 6
Now i want 4 the line from above (ie) N now want line 2
output_line = line 2
PS: I dont want to read the file from bottom.
You can keep a list of the last 4 lines while iterating over the lines of your file. A good way to do it is to use a deque with a maximum length of 4:
from collections import deque
last_lines = deque(maxlen=4)
with open('test.txt') as f:
for line in f:
if line.endswith('6\n'): # Your real condition here
print(last_lines[0])
last_lines.append(line)
# Output:
# line 2
Once a bounded length deque is full, when new items are added, a
corresponding number of items are discarded from the opposite end.
We read the file line by line and only keep the needed lines in memory.
Imagine we have just read line 10. We have lines 6 to 9 in the queue.
If the condition is met, we retrieve line 6 at the start of the queue and use it.
We append line 10 to the deque, the first item (line 6) gets pushed out, as we are sure that we won't need it anymore, we now have lines 7 to 10 in the queue.
My approach would be converting the contents to a list splitting on \n and retrieving required line by index.
lines = '''line 1
line 2
line 3
line 4
line 5
line 6'''
s = lines.split('\n')
current_line = 'line 6'
output_line = s[s.index(current_line) - 4]
# line 2
Since you are reading from file, you don't need to explicitly split on \n. You could read from file as list of lines using readlines:
with open('path/to/your_file') as f:
lines = f.readlines()
current_line = 'line 6'
output_line = lines[lines.index(current_line) - 4]
# line 2
You can use enumerate for your open(). For example:
with open('path/to/your.file') as f:
for i, line in enumerate(f):
# Do something with line
# And you have the i as index.
To go back to the i-4 line, you may think about using while.
But why do you need to go back?
you can do:
with open("file.txt") as f:
lines = f.readlines()
for nbr_line, line in enumerate(lines):
if line == ...:
output_line = lines[nbr_line - 4] # !!! nbr_line - 4 may be < 0
As I can see you are reading the file line by line. I suggest you to read whole file into the list as below example.
with open("filename.txt","r") as fd:
lines=fd.readlines() # this will read each line and append it to lines list
lines[line_number] will give you the respected line.
f.readLines not effective solution. If you work on huge file why do you want to read all file into memory?
def getNthLine(i):
if i<1:
return 'NaN';
else:
with open('temp.text', 'r') as f:
for index, line in enumerate(f):
if index == i:
line = line.strip()
return line
f = open('temp.text','r');
for i,line in enumerate(f):
print(line.strip());
print(getNthLine(i-1));
There is no much more options to solve that kind of a problem.
you could also use tell and seek methods to play around but generally no need for ninja :).
If you using on huge file just do not forget to use enumerate
This is how you could do it with a generator, avoids reading the whole file into memory.
Update: used collections.deque (deque stands for "double ended queue") as recommended by Thierry Lathuille.
import collections
def file_generator(filepath):
with open(filepath) as file:
for l in file:
yield l.rstrip()
def get_n_lines_previous(filepath, n, match):
file_gen = file_generator(filepath)
stored_lines = collections.deque('',n)
for line in file_gen:
if line == match:
return stored_lines[0]
stored_lines.append(line)
if __name__ == "__main__":
print(get_n_lines_previous("lines.txt", 4, "line 6"))
This is my code:
f = gzip.open('nome_file.gz','r')
line = f.readline()
for line in f:
line = f.readline()
line = line.strip('\n')
if not line: break
elements = line.split(" ")
print elements[0]," ",elements[1]," ",elements[44]," ",elements[45]
f.close()
I really don't know why just one line over two is read.
for line in f: reads a line. The next line line = f.readline() reads the next line and stores it in the same variable.
You read every line, but skip every second one.
Simply dropping line = f.readline() should solve the problem.
I have textfiles that have the date stored on line 7 of each file, formatted as such:
Date: 1233PM 14 MAY 00
I would like to search through each file and get the new line 7 to be formatted as such:
Date: 1233PM 14 MAY 2000
So, basically, I just need to stick a '20' in front of the last two digits in line seven.
Probably not the most difficult problem, but I have been having difficulty as textfile.readlines() reads everything into the first (textfile[0]) position.
You can read all the file, change the specified line then save it again:
arc = open('file_name.txt').readlines()[0].split('\r')
#Do what you want with the 7th line i.e. arc[6]
new_arc = open('file_name.txt','w')
for line in arc:
new_arc.write(line)
new_arc.write('\n')
new_arc.close()
Maybe this:
with open(filename, 'r') as f:
lines = f.readlines()
with open(filename, 'w') as f:
for idx, line in lines:
if idx == 7: # or 6
vals = line.split()
if len(vals[-1]) == 2:
vals[-1] = '20'+vals[-1]
line = ' '.join(vals)
f.write(line)
Try this:
# open file
f = open("file.txt" , 'rU+b')
lines = f.readlines()
# modify line 7
lines[6] = lines[6][:-2] + "20" + lines[6][-2:]
# return file pointer to the top so we can rewrite the file
f.seek(0)
f.truncate()
# write the file with new content
f.write(''.join(lines))
f.close