everyone!
I have one file containing one column with only numbers (Paramkey.txt) and i need to read the file and get distinct values and write them in another .txt file. Can someone help with the code? So far the code looks like this
infile=open("Paramkey.txt", "r")
outfile=open("distkey.txt", "w")
for line in infile:
outfile.write(set(infile)
else:
pass
infile.close()
outfile.close()
And i get Syntax error, something with the else statement.
So i managed to finish the program and it's working:
infile=open("Paramkey.txt", "r")
outfile=open("distkey.txt", "w")
for line in infile:
output=set(line.strip() for line in infile)
print >> outfile, "distincts:", output
infile.close()
outfile.close()
and i just want to add i used the "print >>" instead of "print()" statement, because my python is version 2.7.x not 3.x
Related
I want to iterate over all lines in a file with the following script
import sys
infile = open("test.txt")
infile.read()
for line in infile
if line.find("This") != -1
print line
infile.close()
Unfortunately, I am getting this error message:
File "getRes.py", line 6
for line in infile
^
SyntaxError: invalid syntax
I've been trying for an hour to figure out what is the error and I am still not able to find it. Can you tell me what is wrong and how to fix it?
PS: I am using Python 2.7.8, I would like to use this old version instead of a more recent version.
You need a colon after any line that introduces a block in Python.
for line in infile:
if line.find("This") != -1:
There's another mistake in your code, you don't need:
infile.read()
Because it reads all contens of infile and doesn't save it to any variable. And what is more important it moves you to the end of file, so there's no more lines to read.
In addition there's no need to manualy close file, it's better to use with statement:
with open("test.txt") as infile:
for line in infile:
# do what you want
# here file will be close automaticaly, when we exit "with" scope.
Would like to use a text file containing multiple windows path/filename.txt files and feed into a for loop which would then take each path leading to a filename.txt and search it for a word. This would happen for each path to a file in the filename.txt file.
So far this part is functioning:
with open ("filename.txt", "r") as myfile:
data=myfile.read()
print (data)
Printing the data gives me this:
The results of printing out the contents of the variable, "data" looks like:
c:/temp\Txt_folder\3rd_lyr_fldr\3rd_infiles.txt
c:/temp\Txt_folder\3rd_lyr_fldr\3rd_ListFile.txt
c:/temp\Txt_folder\3rd_lyr_fldr\3rd_new_filename1.txt
This part of script ,shown below, does not work. The data shown above is not fed into the for loop (shown below) one line at a time but rather one continuous column or at least
that is the way print(data) shows it on my screen.
for line in data:
if re.search(r"something",line):
print(line)
How can this me accomplished.
Here's something that basically does what you want:
keyword = 'whatever'
with open ('filename.txt', 'rt') as myfile:
for filename in (line.strip() for line in myfile):
with open(filename, 'rt') as file:
for line in file:
if keyword in line:
print(line, end='')
I would like to make it so that it opens up alan.txt, search the text for all instance of scholary_tehologian and if found, add the word "test" under it. when I tried doing it this way:
## Script
with open('alan.txt', 'r+') as f:
for line in f:
if "scholarly_theologian" in line:
f.write("test")
it wouldn't write anything. I'm in Windows 8.1
You can't modify a file like this. You can only append to it, write characters instead of others, or rewrite it entirely. See How do I modify a text file in Python?.
What you should do is create another file with the content you want.
EDIT:
Claudio's answer has the code for what I offered. It has the benefit (over manicphase's code) of not keeping the whole file in memory. This is important if the file is long. manicphase's answer, on the other hand, has the benefit of not creating a second file. It rewrites the original one. Choose the one that fits your needs.
Rewritten answer because the last one was wrong.
If you want to read lines you have to put .readlines() after open(...) or f. Then there's a few ways you could insert "test".
## Script
with open('alan.txt', 'r') as f:
lines = f.readlines()
for i in range(len(lines)):
if "scholarly_theologian" in lines[i]:
lines[i] = lines[i] + "\ntest"
with open('alan.txt', 'w') as f:
f.write("\n".join(lines))
This should do the trick:
with open('output.txt', 'w') as o:
with open('alan.txt', 'r') as f:
for line in f:
o.write(line)
if line.find('scholarly_theoligian'):
o.write('test')
Like Ella Shar mentioned, you need to create a new file and add the new content into it.
If working with two files is not acceptable, the next step would be to delete the input file, and to rename the output file.
outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.flush()
os.fsync(outfile)
outfile.close
This is the code snippet. I am trying to write something into a file in python. but when we open the file, nothing is written into it. Am i doing anything wrong?
You are not calling the outfile.close method.
No need to flush here, just call close properly:
outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.close()
or better still, use the file object as a context manager:
with open(inputfile, 'w') as outfile:
outfile.write(argument)
This is all presuming that argument is not an empty string, and that you are looking at the right file. If you are using a relative path in inputfile what absolute path is used depends on your current working directory and you could be looking at the wrong file to see if something has been written to it.
Try with
outfile.close()
note the brackets.
outfile.close
would only return the function-object and not really do anything.
You wont see the data you have written into it until you flush or close the file. And in your case, you are not flushing/closing the file properly.
* flush the file and not stdout - So you should invoke it as outfile.flush()
* close is a function. So you should invoke it as outfile.close()
So the correct snippet would be
outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.flush()
outfile.close()
I am a beginner and just started learning Python couple days ago (yay!)
so i've come across a problem. when i run, this code outputs everything but the text (txt in file is numbers 0-10 on seperate lines)
def output():
xf=open("data.txt", "r")
print xf
print("opened, printing now")
for line in xf:
print(xf.read())
print("and\n")
xf.close()
print("closed, done printing")
You don't use line, try:
with open('data.txt') as f:
for line in f:
print line
This should print out each number on its own line, like you want, in a lot less code, and more readable.
def output():
f = open('data.txt', 'r').read()
print f
When you used for line in xf: you basically already iterated over the file, implicitly reading each line.
All you need to do is print it:
for line in xf:
print(line)
The reason you aren't seeing the line output is because you aren't telling it to output the line. While iterating over values of line, you print xf.read(). The following is your function rewritten with this in mind. Also added is the use of a with statment block to automatically close the file when you're done with it.
(Using xf.close() is not wrong, just less pythonic for this example.)
def output():
with open("data.txt", "r") as xf:
print xf
print("opened, printing now")
for line in xf:
print(line)
print("and\n")
print("closed, done printing")
You have read the line of text into the variable line in the code for line in xf: so you need to show that e.g. print(line)
I would look at tutorials like the python.org one