i tried using the .strip() method which give me the line
f = open("myFile.txt")#this open myfile
for i in range(500): # print 500 character
line = f.readline().strip()
print(line)
my expected result is
"faowijfaoijfaoiwjfioawjfafawjfaoiwjfawofjafw"
You can do this.
with open("myFile.txt") as f:
chars_100 = f.read(100)
print (chars_100)
Related
I'm trying to modify a specific line in a js file using python.
Here's the js file :
...
hide: [""]
...
Here's my python code :
with open('./config.js','r') as f:
lines = f.readlines()
with open('./config.js','w') as f:
for line in lines:
line = line.replace('hide', 'something')
f.write(line)
So it works but this is not what I want to do.
I want to write 'something' between the brackets and not replace 'hide'.
So I don't know how to do it: Do I have to replace the whole line or can I just add a word between the brackets?
Thanks
If you want to replace text at this exact line you could just do:
with open('./config.js','r') as f:
lines = f.readlines()
with open('./config.js','w') as f:
new_value = 'Something New'
for line in lines:
if line.startswith('hide'):
line = 'hide: ["{}"]'.format(new_value)
f.write(line)
or alternatively in the conditional
if line.startswith('hide'):
line = line.replace('""', '"Something new"')
Here's way to replace any value in brackets for hide that starts with any spacing.
lines = '''\
first line
hide: [""]
hide: ["something"]
last line\
'''
new_value = 'new value'
for line in lines.splitlines():
if line.strip().startswith('hide'):
line = line[:line.index('[')+2] + new_value + line[line.index(']')-1:]
print(line)
Output:
first line
hide: ["new value"]
hide: ["new value"]
last line
You can use fileinput and replace it inplace:
import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
replaceAll("config.js",'hide: [""]','hide: ["something"]')
Reference
If hide: [""] is not ambiguous, you could simply load the whole file, replace and write it back:
newline = 'Something new'
with open('./config.js','r') as f:
txt = f.read()
txt = txt.replace('hide: [""]', 'hide: ["' + newline + '"]')
with open('./config.js','w') as f:
f.write(txt)
As long as you don't have "hide" anywhere else in the file, then you could just do
with open('/config.js','r') as f:
lines = f.readlines()
with open('./config.js','w') as f:
for line in lines:
line = line.replace('hide [""]', 'hide ["something"]')
f.write(line)
You can do this using re.sub()
import re
with open('./config.js','r') as f:
lines = f.readlines()
with open('./config.js','w') as f:
for line in lines:
line = re.sub(r'(\[")("\])', r'\1' + 'something' + r'\2', line)
f.write(line)
It works by searching for a regular expression, but forms a group out of what you want on the left ((\[")) and the right (("\])). You then concatenate these either side of the text you want to insert (in this example 'something').
The bounding ( ) makes a group which can be accessed in the replace with r'\1', then second group is r'\2'.
I have a text file with 300 lines.
I am looking for a word "ABC" in each line
If this word is found i want to print the line before it was found and then the next X lines.
This is the code i have so far but i don't know how to print based on given problem statement.
path = ('C:\\Users\\40081\\PycharmProjects\\datalog_parsing')
count2=1
count1=1
num_lines = open('BBCnt123.txt').read().count('\n')
print (num_lines)
count2=count1
while count2<=num_lines:
file_name = open("BBCnt123.txt", 'r+')
f= open('BBCnt1234' + '.txt', 'w+')
for line_no, line in enumerate (file_name):
line=f.readlines()
if "BBCnt" in line:
f.writelines((line[count2-1]) )
count2= count2+1
file_name.close()
f.close()
with open("file.txt","r") as f:
lines=f.readlines()
[print(lines[c-1]+lines[c:c+X]) for c,e in enumerate(lines) if "ABC" in e]
Try this list comprehension
I have key words to be search in one file let say abc.txt and in another file I have my data, def.txt.
I want a code in python to find key words written in abc.txt, in def.txt and if present, print those line in a new file.
Thank you.
I tried writing a code but it didn't work.
following is the code I write.
f = open('/home/vivek/Documents/abc.txt')
f1 = open('output.txt', 'a')
f2 = open('/home/vivek/Documents/def.txt', 'r')
# doIHaveToCopyTheLine=False
for line in f.readlines():
if f2 in line:
f1.write(line)
f1.close()
f.close()
f2.close()
Load the keywords into a list then you can check the other file line-by-line, and write to outfile as you find keywords in the line.
with open('/path/to/keywords.txt') as f:
keywords = set(line.strip() for line in f) # assuming words are separated by line
with open('/path/to/search_me.txt') as f, open('/path/to/outfile.txt', 'w') as outfile:
for line in f:
if any(kw in line for kw in keywords):
outfile.write(line)
You should record all the words in abc.txt use a set and then search them in def.txt
word_set = set()
with open('/home/vivek/Documents/abc.txt') as f:
for line in f:
word_set.add(line.strip())
f1 = open('output.txt', 'a')
with open('/home/vivek/Documents/def.txt') as f:
for line in f:
find = False
for word in word_set:
if word in line:
find = True
break
if find:
f1.write(line)
f1.close()
You can try this code:
with open("keyword.txt", "r") as keyword_file:
keywords = keyword_file.read().strip()
keywords = keywords.split()
with open("data.txt", "r") as data_file, open("output.txt", "w") as output_file:
for line in data_file.readlines():
line = line.strip()
for word in keywords:
if line.find(word) != -1:
print line
output_file.writelines(line + '\n')
break
In addition to sytech's answer you may try this:
with open('def.txt') as kw_obj, open('abc.txt') as in_obj:
keywords = set(kw_obj.read().split())
in_lines = in_obj.readlines()
match_lines = [line for keyword in keywords for line in in_lines if keyword in line]
if match_lines:
with open('out.txt', 'w') as out:
out.write(''.join(match_lines))
I'm trying to replace a value in a specific line in a text file.
My text file contains count of the searchterm, searchterm & date and time
Text file:
MemTotal,5,2016-07-30 12:02:33,781
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
How can I replace for example the count of the searchterm for line 2 (model name,3,2016-07-30 13:37:59,074)?
This is what I have already:
f = open('file.log','r')
filedata = f.read()
f.close()
newdata = filedata.replace("2", "3")
f = open('file.log', 'w')
f.write(newdata)
f.close()
It replace all values 2.
You have to change three things in your code to get the job done:
Read the file using readlines.
filedata = f.readlines()
Modify the line you want to change (keep in mind that Python indices start at 0 and don't forget to add a newline character \n at the end of the string):
filedata[1] = 'new count,new search term,new date and time\n'
Save the file using a for loop:
for line in filedata:
f.write(line)
Here is the full code (notice I used the with context manager to open/close the file):
with open('file.log', 'r') as f:
filedata = f.readlines()
filedata[1] = 'new count,new search term,new date and time\n'
with open('file.log', 'w') as f:
for line in filedata:
f.write(line)
My solution:
count = 0
line_number = 0
replace = ""
f = open('examen.log','r')
term = "MemTotal"
for line in f.read().split('\n'):
if term in line:
replace= line.replace("5", "25", 1)
line_number = count
count = count + 1
print line_number
f.close()
f = open('examen.log','r')
filedata = f.readlines()
f.close()
filedata[line_number]=replace+'\n'
print filedata[line_number]
print filedata
f = open('examen.log','w')
for line in filedata:
f.write(line)
f.close()
You only need to define the searchterm & the replace value
Input.txt File
12626232 : Bookmarks
1321121:
126262
Here 126262: can be anything text or digit, so basically will search for last word is : (colon) and delete the entire line
Output.txt File
12626232 : Bookmarks
My Code:
def function_example():
fn = 'input.txt'
f = open(fn)
output = []
for line in f:
if not ":" in line:
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
Problem: When I match with : it remove the entire line, but I just want to check if it is exist in the end of line and if it is end of the line then only remove the entire line.
Any suggestion will be appreciated. Thanks.
I saw as following but not sure how to use it in here
a = "abc here we go:"
print a[:-1]
I believe with this you should be able to achieve what you want.
with open(fname) as f:
lines = f.readlines()
for line in lines:
if not line.strip().endswith(':'):
print line
Here fname is the variable pointing to the file location.
You were almost there with your function. You were checking if : appears anywhere in the line, when you need to check if the line ends with it:
def function_example():
fn = 'input.txt'
f = open(fn)
output = []
for line in f:
if not line.strip().endswith(":"): # This is what you were missing
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
You could have also done if not line.strip()[:-1] == ':':, but endswith() is better suited for your use case.
Here is a compact way to do what you are doing above:
def function_example(infile, outfile, limiter=':'):
''' Filters all lines in :infile: that end in :limiter:
and writes the remaining lines to :outfile: '''
with open(infile) as in, open(outfile,'w') as out:
for line in in:
if not line.strip().endswith(limiter):
out.write(line)
The with statement creates a context and automatically closes files when the block ends.
To search if the last letter is : Do following
if line.strip().endswith(':'):
...Do Something...
You can use a regular expression
import re
#Something end with ':'
regex = re.compile('.(:+)')
new_lines = []
file_name = "path_to_file"
with open(file_name) as _file:
lines = _file.readlines()
new_lines = [line for line in lines if regex.search(line.strip())]
with open(file_name, "w") as _file:
_file.writelines(new_lines)