How to read a particular line of text file in python? [duplicate] - python

This question already has answers here:
Search for a word in file & print the matching line - Python
(2 answers)
search value for key in file using python
(2 answers)
Parse key value pairs in a text file
(7 answers)
Closed 2 months ago.
I have a text file with data
Theme="dark_background"
Color="Blue"
Now from the text file I just want to read the value of a Theme in python i.e dark_background
with open("nxc.txt","r") as f:
asz = f.read()
Above is the code for reading whole text file

Don't call .read() (which slurps the whole file when you only need one line), just loop over the file object itself (which is an iterator of its lines) until you find the line you care about:
with open("nxc.txt") as f:
for line in f:
name, sep, value = line.rstrip().partition('=') # Remove trailing whitespace, split on = at most once
if sep and name == 'Theme': # Cheap to confirm it split by check if sep non-empty, then check if found correct name
break # You found it, break out of the loop
# value contains whatever is to the right of the equals after Theme
print(value)

Something like this,
Theme=""
Color=""
with open('c:\\config.file') as f:
for line in f:
if line.startswith("Theme"):
Theme = line.split("=")[1].strip()
if line.startswith("Color"):
Color = line.split("=")[1].strip()

If you just want to read the first line of a file, you can use readline()
eg.
with open("nxc.txt","r") as f:
asz = f.readline()
If you want to read a particular value, you have no choice but to load the whole file and parse it in Python. This is because Python has no idea about the overall structure of the file.

Related

How does not adding a new line erase lines below it [duplicate]

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.

Need to find out how can i write to a .txt file so that the latest results are appended starting from the beginning of the file [duplicate]

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)

Iterate through a file lines in python [duplicate]

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.

Read TXT file line by line - Python [duplicate]

This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 5 years ago.
How can I tell python to read a txt list line by line?
I'm using .readlines() which doesn't seem to be working.
import itertools
import string
def guess_password(real):
inFile = open('test.txt', 'r')
chars = inFile.readlines()
attempts = 0
for password_length in range(1, 9):
for guess in itertools.product(chars, repeat=password_length):
attempts += 1
guess = ''.join(guess)
if guess == real:
return input('password is {}. found in {} guesses.'.format(guess, attempts))
print(guess, attempts)
print(guess_password(input("Enter password")))
The test.txt file looks like:
1:password1
2:password2
3:password3
4:password4
currently the program only works with the last password on the list (password4)
if any other password is entered it will run past all the passwords on the list and return "none".
So I assume I should be telling python to test each line one at a time?
PS. the "return input()" is an input so that the dialog box doesn't close automatically, there's nothing to be inputted.
readlines returns a list of strings with all remaining lines in the file. As the python docs state you could also use list(inFile) to read all ines (https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects)
But your problem is that python reads the line including the newline character (\n). And only the last line has no newline in your file. So by comparing guess == real you compare 'password1\n' == 'password1' which is False
To remove the newlines use rstrip:
chars = [line.rstrip('\n') for line in inFile]
this line instead of:
chars = inFile.readlines()
First of all try to search duplicated posts.
How do I read a file line-by-line into a list?
For example, what I am usually using when working txt files:
lines = [line.rstrip('\n') for line in open('filename')]

How do I read each line of a file and add if statements? [duplicate]

This question already has answers here:
How to read a file without newlines?
(12 answers)
How can I read inputs as numbers?
(10 answers)
Closed 7 months ago.
I'm pretty new to Python, but I'm trying to learn. One idea I had for a simple script was to have a script that reads and writes to a log file during execution. Then based on what's in that log file, helps dictate what the script does the next time it's ran.
Reading and writing to a file seems simple enough in Python,
f = open('textfile.txt', 'r+')
Reading and print out each line of a file seems simple too,
for line in f:
print line
line=f.next()
print line
But, how do I incorporate an IF statement when reading a file to do something based on what was read?
for line in f
if line == '1':
print "Works!"
else:
print line
line=f.next()
print line
f.close()
Output
1
2
3
4
5
The problem is that line is equal to
'1\n'
You first need to remove the newline character by doing first in your loop:
line = line.rstrip()
Another possibility could be, in this particular case in which you expect integers, to cast the line string into an integer, and then to compare to an integer:
line = int(line)
if line == 1:
# and so on

Categories

Resources