In python how we can select second line string of a text file.
I have a text file and in that file there are some data in line by line_
Dog
Cat
Cow
How to fetch the second line which is “Cat” and store that string in a variable.
f = open(“text_file.txt”, “r”)
var = # “Cat”
Can I use single line code without using any loop or anything like we open a file using this single line of code f = open(“text_file.txt”, “r”)
I'd suggest the following
with open('anim.txt','r') as f:
var = f.readlines()[1].strip()
print(var)
[1] get the second line
.strip() removes the new line character from the end of the string
with open... safely opens/closes the file
Open your file in this mode:
f = open('x.txt','r+',encoding='utf-8')
You can then read the files line by line:
f.readlines()
Related
I tried to write a code that removes any line from a file that starts with a number smaller than T and which then writes the remaining lines to another file.
def filter(In,Out, T):
with open(In,'r') as In:
with open(Out,'r') as Out:
lines=In.readlines()
lines=[[e for e in line.split()] for line in lines]
lines=[line for line in lines if int(line[0])>=T]
for line in lines:
for word in line:
Out.write(f"{word} ")
return None
I thought The code would probably write the words in one long line instead of putting it per line but it just returned UnsupportedOperation: not writable and I don't understand why.
it seems like your code had a few bugs
you opened the file for reading with the line with open(Out,'r') as Out: and then tried to write to the file, so I changed the r to w
you tried to open the file for writing when it was already open for reading (you cant open a file while it's open) so i moved the code the writes back to the file to be after you have finished reading from it
you open the file for reading and gave it the name In but this name is already the name of an argument that you function is getting
this should do the trick:
def filter(In_name,Out, T):
with open(In_name,'r') as In:
lines=In.readlines()
lines=[[e for e in line.split()] for line in lines]
lines=[line for line in lines if int(line[0])>=T]
with open(Out, 'w') as Out:
for line in lines:
for word in line:
Out.write(f"{word} ")
return None
I have a very big txt file with uneven data lines. I want to delete a specific line from the txt file, but all methods shown in google shows to
Read the file to get all lines
Delete the specific line
Write to the file again
I want to know if there is any method in Python that I can use to delete the line from text file without having to write again.
#get list of lines.
a_file = open("sample.txt", "r")
lines = a_file. readlines()
a_file. close()
#remove line from list
del lines[1]
#write new contents into file
new_file = open("sample.txt", "w+")
for line in lines:
new_file. write(line)
new_file. close()
I am trying to encrypt 1 file and save the encrypted text from the first file into another file. I have it all working besides that it is only writing 1 line into the new file instead of the entire file.
file1 = open("passwords-plainText", "r")
for line in file1:
file2 = open("encryptedfile.txt", "w")
file2.write(encryptVignere(keyGen(), line))
The example file I am using looks like this
example
secondexample
new line
this is another new line
The output into the new file I am saving to only writes the first line and not the rest of the lines
ie.)
tyawakud
The file should look like this instead...
tyawakud
tqiibwaeeonozp
pttzucfqs
foxnzgjwtmbhnpwhjnapmsfg
You should only open file2 once:
file1 = open("passwords-plainText", "r")
file2 = open("encryptedfile.txt", "w")
for line in file1:
file2.write(encryptVignere(keyGen(), line))
Otherwise you just keep overwriting it.
I want to read the input file, line by line, then modify one line and write back the changes to the same file
the problem is that, after writing back, I lose the return to the line and I have all the data in one line
open(bludescFilePath, 'a+') as blu:
blu_file_in_lines = blu.readlines()
for line in blu_file_in_lines:
if "Length" in line:
blu_file_in_lines[13] = line.replace("0x8000",str(size))
with open(bludescFilePath, 'w') as blu:
blu.write(str(blu_file_in_lines))
EDIT
Ok, what was missing is the for loop.
with open(bludescFilePath, 'w') as blu:
for line in blu_file_in_lines:
blu.write(str(line))
I have a file that is formatted with different indentation and which is several hundred lines long and I have tried various methods to load it into python as a file and variable but have not been successful. What would be an efficient way to load the file. My end goal is to load the file, and and search it for a specific line of text.
with open('''C:\Users\Samuel\Desktop\raw.txt''') as f:
for line in f:
if line == 'media_url':
print line
else:
print "void"
Error: Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> with open('''C:\Users\Samuel\Desktop\raw''') as f: IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Users\\Samuel\\Desktop\raw
If you're trying to search for a specific line, then it's much better to avoid loading the whole file in:
with open('filename.txt') as f:
for line in f:
if line == 'search string': # or perhaps: if 'search string' in line:
# do something
If you're trying to search for the presence of a specific line while ignoring indentation, you'll want to use
if line.strip() == 'search string'.strip():
in order to strip off the leading (and trailing) whitespace before comparing.
The following is the standard way of reading a file's contents into a variable:
with open("filename.txt", "r") as f:
contents = f.read()
Use the following if you want a list of lines instead of the whole file in a string:
with open("filename.txt", "r") as f:
contents = list(f.read())
You can then search for text with
if any("search string" in line for line in contents):
print 'line found'
Python uses backslash to mean "escape". For Windows paths, this means giving the path as a "raw string" -- 'r' prefix.
lines have newlines attached. To compare, strip them.
with open(r'C:\Users\Samuel\Desktop\raw.txt') as f:
for line in f:
if line.rstrip() == 'media_url':
print line
else:
print "void"