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.
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)
I am working on NLP project and have extracted the text from pdf using PyPDF2. Further, I removed the blank lines. Now, my output is being shown on the console but I want to populate the text file with the same data which is stored in my variable (file).
Below is the code which is removing the blank lines from a text file.
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file=line
print(file)
Output on Console:
Eclipse,
Visual Studio 2012,
Arduino IDE,
Java
,
HTML,
CSS
2013
Excel
.
Now, I want the same data in my (resume1.txt) text file. I have used three methods but all these methods print a single dot in my resume1.txt file. If I see at the end of the text file then there is a dot which is being printed.
Method 1:
with open("resume1.txt", "w") as out_file:
out_file.write(file)
Method 2:
print(file, file=open("resume1.txt", 'w'))
Method 3:
pathlib.Path('resume1.txt').write_text(file)
Could you please be kind to assist me in populating the text file. Thank you for your cooperation.
First of all, note that you are writing to the same file losing the old data, I don't know if you want to do that. Other than that, every time you write using those methods, you are overwriting the data you previously wrote to the output file. So, if you want to use these methods, you must write just 1 time (write all the data).
SOLUTIONS
Using method 1:
to_file = []
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
to_file.append(file)
to_save = '\n'.join(to_file)
with open("resume1.txt", "w") as out_file:
out_file.write(to_save)
Using method 2:
to_file = []
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
to_file.append(file)
to_save = '\n'.join(to_file)
print(to_save, file=open("resume1.txt", 'w'))
Using method 3:
import pathlib
to_file = []
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
to_file.append(file)
to_save = '\n'.join(to_file)
pathlib.Path('resume1.txt').write_text(to_save)
In these 3 methods, I have used to_save = '\n'.join(to_file) because I'm assuming you want to separate each line of other with an EOL, but if I'm wrong, you can just use ''.join(to_file) if you want not space, or ' '.join(to_file) if you want all the lines in a single one.
Other method
You can do this by using other file, let's say 'output.txt'.
out_file = open('output.txt', 'w')
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
out_file.write(file)
out_file.write('\n') # EOL
out_file.close()
Also, you can do this (I prefer this):
with open('output.txt', 'w') as out_file:
for line in open('resume1.txt'):
line = line.rstrip()
if line != '':
file = line
print(file)
out_file.write(file)
out_file.write('\n') # EOL
First post on stack, so excuse the format
new_line = ""
for line in open('resume1.txt', "r"):
for char in line:
if char != " ":
new_line += char
print(new_line)
with open('resume1.txt', "w") as f:
f.write(new_line)
I have a function which reads a file line by line and inserts it into a textinput:
def load_list(self, path, filename):
self.text_from_file.text = ''
with open(filename[0], 'r') as file:
line = file.readline()
cnt = 1
while line:
sentence = "{}".format(line.strip())
self.text_from_file.text += sentence + "\n"
line = file.readline()
cnt += 1
self.dismiss_popup()
Now file content is stored in text_from_file variable, which is text_from_file = ObjectProperty(None) type (I am using kivy).
What I want to do is read the text from textinput (text_from_file.text) and add every line into a list, so one line will be one item in the list. How can I read textinput line by line? Does it work the same as from file? I do not want to do it right away in the function above. I want to do it later in a separate function.
An easy way to get all lines from a file into a list is like this:
with open(filename, 'r') as f:
lines = [line for line in f]
# do something with lines
EDIT:
To read a variable line by line, just split it by '\n' and iterate over the result:
for line in self.text_from_file.text.split('\n'):
print(line)
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.
I have a text file like this:-
V1xx AB1
V2xx AC34
V3xx AB1
Can we add ; at each end of line through python script?
V1xx AB1;
V2xx AC34;
V3xx AB1;
Here's what you can try. I have overwritten the same file though.
You can try creating a new one(I leave it to you) - You'll need to modify your with statement a little : -
lines = ""
with open('D:\File.txt') as file:
for line in file:
lines += line.strip() + ";\n"
file = open('D:\File.txt', "w+")
file.writelines(lines)
file.flush()
UPDATE: - For in-place modification of file, you can use fileinput module: -
import fileinput
for line in fileinput.input('D:\File.txt', inplace = True):
print line.strip() + ";"
input_file_name = 'input.txt'
output_file_name = 'output.txt'
with open(input_file_name, 'rt') as input, open(output_file_name, 'wt') as output:
for line in input:
output.write(line[:-1]+';\n')
#Open the original file, and create a blank file in write mode
File = open("D:\myfilepath\myfile.txt")
FileCopy = open("D:\myfilepath\myfile_Copy.txt","w")
#For each line in the file, remove the end line character,
#insert a semicolon, and then add a new end line character.
#copy these lines into the blank file
for line in File:
CleanLine=line.strip("\n")
FileCopy.write(CleanLine+";\n")
FileCopy.close()
File.close()
#Replace the original file with the copied file
File = open("D:\myfilepath\myfile.txt","w")
FileCopy = open("D:\myfilepath\myfile_Copy.txt")
for line in FileCopy:
File.write(line)
FileCopy.close()
File.close()
Notes: I have left the "copy file" in there as a back up. You can manually delete it or use os.remove() (if you do that don't forget to import the os module)