This question already has answers here:
How to search for a string in text files?
(13 answers)
Closed 12 months ago.
Hello, so, i'm having trouble to find if text file contains string.
for example.
and i want to create program to check if this file contains string 'banana'.
i have tried this but it didn't work
with open("test.txt","r") as f:
content = f.read()
for line in content:
if 'banana' in line:
do_something()
else:
exit()
text file looks like this:
banana is yellow
apple is red
python is good
You don't need looping 'cause your file is just text, so just use conditional
with open("test.txt","r") as f:
content = f.read()
if 'banana' in content:
do_something()
else:
exit()
Related
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.
This question already has answers here:
Read only the first line of a file?
(8 answers)
Closed 3 months ago.
I am currently working with file handling in Python.
I have problem in copying the string value of the file.
I wanted to copy the string from file and store it to a variable, just like in C
example: this is how we do in C
FILE *fptr = fopen("read.txt", "r");
fgets(charVar, 100, fptr);
where we store the string file to charVar.
So is there a fgets() function equivalent to python?
You can pass the limit argument to readline for a file object which would have similar behavior of stopping on a max character or a newline. Example text file:
01234567890123456789
01234567890123456789
with open("test.txt", "r") as f:
while data := f.readline(8):
print("line:", data)
Outputs:
line: 01234567
line: 89012345
line: 6789
line: 01234567
line: 89012345
line: 6789
This question already has answers here:
How to search and replace text in a file?
(22 answers)
Closed 2 years ago.
with open("textfile.txt", 'r+') as fin:
text = fin.read()
fin.write(text.replace(" full stop ","."))
fin.write(text.replace("New Paragraph","\n \t"))
I want to add punctuation in the file. e.g. replace the words "Full Stop" with the actual punctuation mark "." and "New Paragraph" with " \n\t ".
The code is not giving any error but it is not replacing any string
Actually i see you open the file with r+ which will create a new file if it does not exist, and if it will create it will have no content and then it will raise error.
Better is you check first is the file is empty with
import os
if os.stat("filename.txt").st_size == 0:
# ADD SOME CODE HERE TO ADD CONTENT TO FILE
And then add content
This question already has answers here:
Writing Unicode text to a text file?
(8 answers)
Closed 6 years ago.
I try to write to txt file list with russian string.(I get that with unique1 = np.unique(df['search_term']), it's numpy.ndarray)
thefile = open('search_term.txt', 'w')
for item in unique1:
thefile.write("%s\n" % item)
But in list this string looks correct. But after writing it looks like
предметов berger bg bg045-14 отзывы
звезд
воронеж
Why a get that?
Try writing to the file like this:
import codecs
thefile = codecs.open('search_term.txt', 'w', encoding='utf-8')
for item in unique1:
thefile.write("%s\n" % item)
The problem is that the file likely is encoded correctly hence why the characters will display incorrectly.
This question already has answers here:
Does reading an entire file leave the file handle open?
(4 answers)
Closed 8 years ago.
I need your help. I want to read a text file "as a whole" and not line by line. This is because by doing line by line my regex doesn't work well, it needs the whole text. So far this is what I am being doing:
with open(r"AllText.txt") as fp:
for line in fp:
for i in re.finditer(regexp_v3, line):
print i.group()
I need to open my file, read it all, search if for my regex and print my results. How can I accomplish this?
To get all the content of a file, just use file.read():
all_text = fp.read() # Within your with statement.
all_text is now a single string containing the data in the file.
Note that this will contain newline characters, but if you are extracting things with a regex they shouldn't be a problem.
For that use read:
with open("AllText.txt") as fp:
whole_file_text = fp.read()
Note however, that your test will contain \n where the new-line used to be in your text.
For example, if this was your text file:
#AllText.txt
Hello
How
Are
You
Your whole_file_text string will be as follows:
>>> whole_file_text
'Hello\nHow\nAre\nYou'
You can do either of the following:
>>> whole_file_text.replace('\n', ' ')
'Hello How Are You'
>>> whole_file_text.replace('\n', '')
'HelloHowAreYou'
If you don't want to read the entire file into memery, you can use mmap
Memory-mapped file objects behave like both strings and like file objects.
import re, mmap
with open(r'AllText.txt', 'r+') as f:
data = mmap.mmap(f.fileno(), 0)
mo = re.finditer(regexp_v3, data)