i am writing the below mentioned simple code in python, but it does not open - python

I am writing the below mentioned simple code in python, but it does not open the file(list1.txt), I am using IDLE 3.7.0. When I write the code without the first line it works! What is the problem?
def list_from_file(a="list1.txt"):
file_pointer = open("a", 'r')
data = file_pointer.readlines()
print(data)

This is because the first line def list_from_file(a="list1.txt"): defines a function, everything below and indented (your next 3 lines in this case) belongs to it.
Basically it is a bloc of code in the main program that is only executed if you call it. It you don't it will not execute.
To call a function you have to add a line like this:
def list_from_file(a="list1.txt"):
file_pointer = open(a, 'r')
data = file_pointer.readlines()
print(data)
list_from_file()
Notice how the call is on the same indentation level as the first line, this means that this line does not belong to the function itself and thus will be executed.
Also your function have an optional argument a="list1.txt" Meaning that you can call your function with another file if you want it by calling it that way: list_from_file(a="another_list.txt"), doing so will ignore the default value you put in the function and use the one you gave during the call.
I can also notice something strange, you are storing the file you want to open inside the variable a (see your first line), but on the second line you are opening a file which name is "a", you are not opening the good file, if you want to open the file "list1.txt" you need to change the second line to:
file_pointer = open(a, 'r') # I removed the quotes around the a to use the variable with the filename

def list_from_file(a="list1.txt"):
file_pointer = open(a, 'r')
data = file_pointer.readlines()
print(data)
Remove double quotes or else it takes as string value as a not file name

Related

How to take items in a list, and print them to a new .txt document on separate lines

okay, this may have been talked about before, but I am unable to find it anywhere on stack so here i am.
Basically I am writing a script that will take a .txt document and store every other line (even lines say) and print them into a new text document.
I was able to successfully write my code to scan the text and remove the even numbered lines and put them into a list as independent variables but when i got to add each item of the list to the new text documents, depending on where i do that i get either the first line or the last line but never more than one.
here is what i have
f = open('stuffs.txt', 'r')
i = 1
x = []
for line in f.readlines():
if i % 2 == 0:
x.append(line)
i += 1
I have tested that this successfully takes the proper lines and stores them in list x
i have tried
for m in x:
t = open('stuffs2.txt','w')
t.write(m)
directly after, and it only prints the last line
if i do
for line in f.readlines():
if i % 2 == 0:
t = open('stuffs2.txt','w')
t.write(line)
i += 1
it will print the first line
if i try to add the first solution to the for loop as a nested for loop it will also print the first line. I have no idea why it is not taking each individual item and putting it in the .txt
when i print the list it is in there as it should be.
Did look for a canonical - did not find one...
open('stuffs2.txt','w') - "w" == kill whats there and open new empty file ...
Read the documentation: reading-and-writing-files :
7.2. Reading and Writing Files
open() returns a file object, and is most commonly used with two arguments: open(filename, mode). f = open('workfile', 'w')
The first argument is a string containing the filename.
The second argument is another string
containing a few characters describing the way in which the file will
be used.
mode can be 'r' when the file will only be read, 'w' for only
writing (an existing file with the same name will be erased), and 'a'
opens the file for appending; any data written to the file is
automatically added to the end. 'r+' opens the file for both reading
and writing. The mode argument is optional; 'r' will be assumed if
it’s omitted.
To write every 2nd line more economically:
with open("file.txt") as f, open("target.txt","w") as t:
write = True
for line in f:
if write:
t.write(line)
write = not write
this way you do not need to store all lines in memory.
The with open(...) as name : syntax is also better - it will close your filehandle (which you do not do) even if exceptions arise.

Why wasn't my file opened?

I'm working on a project at the end of a book I read for Python, so in case this hasn't given it away for you, I'm still quite new to this.
I'm trying to use the open command to open a file that I know exists. I know that the code understands the file is there, because when I switch over to write mode, it clears my text file out, telling me that it can find the file but it just won't read it. Why is this happening? Here's the code-
openFile = open('C:\\Coding\\Projects\\Python\\One Day Project\\BODMAS\\userScores.txt', 'r')
def getUserPoint(userName):
for line in openFile:
split(',')
print(line, end = "")
I've tried a few variations where my openFile function is a local variable inside getUserPoint(), but that didn't make a difference either.
Editing because I missed a vital detail — the userScores.txt file is laid out as follows:
Annie, 125
The split() function is supposed to split the name and the score assigned to the name.
Your function isn't valid Python, as split isn't a globally defined function, but a built-in function of the type str. Try changing your function to something like this.
def getUserPoint(name):
for line in openFile:
line_split = line.split(",")
print(line_split, end = "")

How to search specific lines in a file and write them to another file, using function in Python

My aim is build a log parser which will copy selected lined between keywords I want and write to a file. Since I would have to search between multiple keywords in single file hence I thought of writing a function and using it multiple times in my script.
However I am unable to achieve this with following script and getting an error:
import re
def myfunc (infile ,outfile, search1 , search2):
fi = infile.readlines()
fo = open(outfile, 'w')
write1 = False
for line in fi:
if re.findall('search1' , str(line)):
write1 = True
elif re.findall('search2', str(line)):
write1 = False
elif write1:
fo.write(line)
fo.close()
fi.close()
return;
text_file = open(input("name of inputfile : "))
resultfile = input("name of outputfile : ")
search1 = "teen"
search2 = "eight"
myfunc (text_file , resultfile , search1 , search2)
I am getting following error:
Traceback (most recent call last):
File "C:/Users/zoro/PycharmProjects/text-parsing/write selected test 2 sets.py", line 38, in <module>
myfunc (text_file , resultfile , search1 , search2)
File "C:/Users/zoro/PycharmProjects/text-parsing/write selected test 2 sets.py", line 28, in myfunc
fi.close()
AttributeError: 'list' object has no attribute 'close'
fi = infile.readlines()
This makes fi a list of lines in the file infile. So when you later call fi.close(), you are trying to close a list, which of course does not work.
Instead, you need to close the file, i.e. infile:
infile.close()
In general, it’s a good idea to change the variable names in a way so it’s obvious what they contain. infile is a file object which you read from, so that’s okay. outfile is a file name of the file you want to write to, so you should name it outFileName or something instead. fi is a list of lines in the infile, so you should call it maybe inFileLines.
You should also avoid having to close file objects manually; instead, use the with statement to make sure that they are closed automatically:
with open(outfile, 'w') as fo:
fo.write('stuff')
# no need to manually close it
Finally, there is another issue with your code: re.findall('search1' , str(line)) This will search for the string 'search1' in the line; it will not respect the values that are being passed to the function and are stored in the search1 (and search2) variables. So you need to remove the quotes there: re.findall(search1, line) (you also don’t need to convert the line to a string).
Also, using re.findall() if you only evaluate its truth-value is not really the best way. Instead, use re.search which only returns the first result (so for really long lines, you wouldn’t keep searching if you already found a result). And if search1 and search2 won’t contain actual regular expressions but just strings you want to find in the line, then you should also just use the in operator:
if search1 in line:
write1 = True
One final note: File handles should always be closed from the same level they are opened from. So if you open a file handle inside a function, then that function should also close it. If you open a file on the outside of the function, then the function should not close it. It is the opener’s responsibility to close the file, and for other instances to close files may result in wrong behavior, so you shouldn’t do it (unless it’s explicitly documented, e.g. a function doSomethingAndClose may close the file).
Using the with statement generally avoids this, as you never call file.close() manually, and the with statement already makes sure that the file is correctly closed.
If you want to consume a file multiple times, then you would have to seek to the beginning in order to be able to read from it again. In your case, since you are using infile.readlines() to read the whole file into memory, it’s a better idea to just read the lines once from the file and then reuse it for multiple function calls:
text_file = input("name of inputfile : ")
with open(text_file) as infile:
fi = infile.readlines() # read the lines *once*
myfunc(fi, …)
myfunc(fi, …)
myfunc(fi, …)

Reading from a file: find the new line

I am trying to read a text file using python. The code is given below:
with open('data.txt') as f:
for line in f:
val=line.split()
It simply reads from a text file and ensures that it reads all the lines at once. I want to change its implementation. Suppose that it is in a function and I have an already opened file, how do I ensure that I read a new line every time I call the function?
I have read about the seek function, can I use it to seek to a new line every time the function is called?
You can use a generator, like this
def get_next_line(file_name):
with open(file_name) as f:
for line in f:
yield line.strip()
and you can get the next line, like this
for line in get_next_line("Input.txt"):
print line
But you want to get the next lines, not in a loop then you can explicitly use next function, like this
my_file = get_next_line("Input.txt")
print next(my_file)
print next(my_file)

Why doesn't this simple search work?

am simply iterating through an external file (which contains a phrase) and want to see if a line exists (which has the word 'Dad' in it) If i find it, I want to replace it with 'Mum'. Here is the program i've built... but am not sure why it isn't working?!
message_file = open('test.txt','w')
message_file.write('Where\n')
message_file.write('is\n')
message_file.write('Dad\n')
message_file.close()
message_temp_file = open('testTEMP.txt','w')
message_file = open('test.txt','r')
for line in message_file:
if line == 'Dad': # look for the word
message_temp_file.write('Mum') # replace it with mum in temp file
else:
message_temp_file.write(line) # else, just write the word
message_file.close()
message_temp_file.close()
import os
os.remove('test.txt')
os.rename('testTEMP.txt','test.txt')
This should be so simple...it's annoyed me! Thanks.
You don't have any lines that are "Dad". You have a line that is "Dad\n", but no "Dad". In addition, since you've done message_file.read(), the cursor is at the end of your file so for line in message_file will return StopIteration immediately. You should do message_file.seek(0) just before your for loop.
print(message_file.read())
message_file.seek(0)
for line in message_file:
if line.strip() == "Dad":
...
That should put the cursor back at the beginning of the file, and strip out the newline and get you what you need.
Note that this exercise is a great example of how not to do things in general! The better implementation would have been:
in_ = message_file.read()
out = in_.replace("Dad","Mum")
message_temp_file.write(out)
print(message_file.read())
here you already read the whole file.
Nothing is left for the for loop to check
A file object always remembers where it stopped to read/write the last time you accessed it.
So if you call print(message_file.readline()), the first line of the file is read and printed. Next time you call the same command, the second line is read and printed and so on until you reach the end of the file. By using print(message_file.read()) you have read the whole file and any further call of read or readline will give you nothing
You can get the current position by message_file.tell() and set it to a certain value by message_file.seek(value), or simply reopen the file
The problem most likely is due to the fact that your conditional will only match the string "Dad", when the string is actually "Dad\n". You could either update your conditional to:
if line == "Dad\n":
OR
if "Dad" in line:
Lastly, you also read the entire file when you call print(message_file.read()). You either need to remove that line, or you need to put a call to message_file.seek(0) in order for the loop that follows to actually do anything.

Categories

Resources