I am currently trying to search for a specific word in a text file.
I've already wrote my code but it seems that the script is not working correctly.
My code:
main_file = open('myfile.txt','w')
x = 'Hello'
x_main = main_file.write(x)
with open('myfile.txt') as f:
datafile = f.readlines()
for line in datafile:
if 'Hello' in line: #I also tried Hello without the quotes
print("ok")
print(x)
I get only Hello as an output and not ok + Hello.
I hope that someone can help me out with this little problem:)
Thank's for every help and suggestion in advance:)
Your main problem is that you don't close the file after your file after writing to it. Like you have done to open your file with open(file) as file you can do the same in order to read the file. This way you avoid the hastle of writing file.close().
Other than that, your code seems fine.
with open('test.txt','w') as f:
x = 'Hello'
f.write(x)
with open('test.txt') as f:
datafile = f.readlines()
for line in datafile:
if 'Hello' in line: #I also tried Hello without the quotes
print("ok")
print(x)
Try this one
main_file = open('myfile.txt','w')
x = 'Hello'
x_main = main_file.write(x)
main_file.close()
with open('myfile.txt', 'r') as f:
datafile = f.readlines()
for line in datafile:
if 'Hello' in line: #I also tried Hello without the quotes
print("ok")
print(x)
When writing to your file, you never closed the file (file.close()). I would suggest using the open() context manager so you don't have to worry about writing file.close().
string = "Hello"
with open("myfile.txt", "w") as file:
file.write(string)
with open("myfile.txt") as file:
lines = file.readlines()
for line in lines:
if "Hello" in line:
print("OK")
print(string)
Related
the code reads from multiple text files so far i have it to display on the terminal but i would like to have the info written into a text file but the text file shows up blank and dont know why new to python so still haven't figured out all the commands.
directory = 'C:\Assignments\\CPLfiles\*'
test = False
start_text = '^GMWE'
for filename in glob.glob(directory):
with open(filename) as f:
with open('file.txt', 'w') as f1:
for line in f:
#for x in line:
if test is False:
if re.search(start_text, line.strip()) is not None:
x = line.strip()
f1.write(x+ '\n')
print(x)
break
test = False
I think you should change the order of opening files to the following.
The problem is that for each file you open to read, you're also re-opening the file to write, whipping it's contents.
Also, due to the break you will write at maximum one line per file due to the break after the write statement.
If the last file that you opened does not have any match with the regular expression, then nothing will exist in the final file.
Hope it makes sense
directory = 'C:\Assignments\\CPLfiles\*'
test = False
start_text = '^GMWE'
with open('file.txt', 'w') as f1:
for filename in glob.glob(directory):
with open(filename) as f:
for line in f:
#for x in line:
if test is False:
if re.search(start_text, line.strip()) is not None:
x = line.strip()
f1.write(x+ '\n')
print(x)
break
test = False
I think that the main problem here is that you reopen file.txt for each file in you globbing. Each time opening it in write mode erases the file. If no line match in the last file you will end up with an empty file as a result. So your loop should be inside your with that opens this file.
I can't close this file, as the file is directly fed into the 'lines'-list.
I have tried closing with command lines.close() but it doesn't work.
def readfile():
lines = [line.rstrip('\n') for line in open('8ballresponses.txt', 'r')]
print(random.choice(lines))
I don't get an error, but i want to be able to close the file.
Instead of file object, lines is a list , so you can't close it. And you should store file object open('8ballresponses.txt', 'r') with a variable for closing it later:
def readfile(file_path):
test_file = open(file_path, 'r')
lines = [line.rstrip('\n') for line in test_file]
test_file.close()
print(random.choice(lines))
Or simply use with "to close a file in python, without a file object":
def readfile(file_path):
with open(file_path, 'r') as test_file:
lines = [line.rstrip('\n') for line in test_file]
print(lines)
you can use with open command. this will automatically handle all the test cases failure etc. (inbuild try except and finally in python)
below is example similiar to your code
import random
def readfile():
lines = []
with open(r"C:\Users\user\Desktop\test\read.txt",'r') as f:
lines = f.readlines()
print(random.choice(lines))
You can use try and finally block to do the work.
For example :
def readfile():
file = open('8ballresponses.txt', 'r')
try:
lines = [line.rstrip('\n') for line in file]
print(random.choice(lines))
finally:
file.close()
In this post
"When the with ends, the file will be closed. This is true even if an exception is raised inside of it."
You manually invoke the close() method of a file object explicitly or implicitly by leaving a with open(...): block. This works of course always and on any Python implementation.
Use with this will close implicitly after the block is complete
with open('8ballresponses.txt', 'r') as file:
lines = [ line.rstrip("\n") for line in file ]
I am reading a text file.
One line from the text file looks like this and comes at the very end of the text file:
</DTS:Executable>
I am using replace("</DTS:Executable>","test from me")
Nothing gets replaced and the text stays as is.
What am I doing wrong?
What is the extension of the file ?
Can you try this sed command :
sed -i 's/original/new/g' file.txt
How about reading the data in list and replacing the last element, like so;
with open(fname) as f:
content = f.readlines()
lines = [line.rstrip('\n') for line in file]
lines[-1] = "test from me"
Did this work?
If the file content are not to large then straight forward you can do something like this
with open(filename) as f:
content = f.read()
content = content.replace("<old>", "<new>")
with open(filename, "w") as f:
f.write(content)
Could someone give me some guidance on how you would get the contents of your text file on my python code without opening up the text file in another window?
Just point me in the right direction on how I should do it (No need for solutions)
with open(workfile, 'r') as f:
for line in f:
print line
If you don't use the context manager (the with statement) you will need to explicitly call f.close(), for example:
f = open('workfile', 'r')
line = f.readline()
print line
f.close()
file = open("your_file.txt", "r")
file.read()
I need some help Im trying to display the text files contents (foobar) with this code
text = open('C:\\Users\\Imran\\Desktop\\text.txt',"a")
rgb = text.write("foobar\n")
print (rgb)
text.close()
for some reason it keeps displaying a number. If anyone could help that would be awesome, thanks in advance
EDIT: I am Working with Python 3.3.
Print the contents of the file like this:
with open(filename) as f:
for line in f:
print(line)
Use with to ensure that the file handle will be closed when you are finished with it.
Append to the file like this:
with open(filename, 'a') as f:
f.write('some text')
# Open a file
fo = open("foo.txt", "r+")
str = fo.read();
print "Read String is : ", str
# Close opend file
fo.close()
More: http://www.tutorialspoint.com/python/python_files_io.htm
You are printing the number of written bytes. That won't work. Also you might need to open the file as RW.
Code:
text = open('...', "a")
text.write("foo\n")
text = open('...', "r")
print text.read()
If you want to display the contents of the file open it in read mode
f=open("PATH_TO_FILE", 'r')
And then print the contents of file using
for line in f:
print(line) # In Python3.
And yes, don't forget to close the file pointer f.close() after you finish the reading