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 = "")
Related
Im really get confused.
Im solving PySchool Practices for university and get a problem at Topic 13: Question 2.
I need to:
Create a function that appends the name and email to the end of a named file.
Code i use:
# Create a function that appends the name and email to the end of a named file.
def addEmail(filename, name, email):
f = open(filename, 'a') # replace the mode
f.write("\n"+name+' '+email)
# Append name and email, each record should end with '\n'.
f.close()
# close file
return f # do not remove this line
I get:
Error
I cant understand where is my mistake.Please help.
Your code puts a newline character at the beginning of the line added to the file. However, it's very likely that the file already has a newline character at the end of the last line to begin with.
Rather you should put you newline character at the end of the line you add. I've tried this variation; it works.
can you check if the file is in the same directory or if it is the full file location. Also I suggest you to use with:
#with will close file automatically when code is done
with open(filename, 'a') as f:
# If using python 3.6 and up you can use f-String formatting
f.write(f'\n{name} {email}')
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
I am a beginner, writing a python script in which I need it to create a file that I can write information to. However, I am having problems getting it to create a new, not previously existing file.
for example, I have:
file = open(coordinates.kml, 'w')
which it proceeds to tell me:
nameerror: name 'coordinates' is not defined.
Of course it isn't defined, I'm trying to make that file.
Everything I read on creating a new file says to take this route, but it simply will not allow me. What am I doing wrong?
I even tried to flat out define it...
file = coordinates.kml
file_open = open(file, 'w')
... and essentially got the same result.
You need to pass coordinates.kml as a string, so place them in quotes (single or double is fine).
file = open("coordinates.kml", "w")
In addition to the above answer,
If you want to create a file in the same path, then no problem or else you need to specify the path as well in the quotes.
But surely opening a file with read permission will throw an error as you are trying to access an nonexistent file.
To be future proof and independent of the platforms you can read and write files in binaries. For example if this is Python on Windows, there could be some alternations done to the end of line. Hence reading and writing in Binary mode should help, using switches "rb" and "wb"
file = open("coordinates.kml", "wb")
And also remember to close the file session, else can throw errors while re running the script.
The Problem - Update:
I could get the script to print out but had a hard time trying to figure out a way to put the stdout into a file instead of on a screen. the below script worked on printing results to the screen. I posted the solution right after this code, scroll to the [ solution ] at the bottom.
First post:
I'm using Python 2.7.3. I am trying to extract the last words of a text file after the colon (:) and write them into another txt file. So far I am able to print the results on the screen and it works perfectly, but when I try to write the results to a new file it gives me str has no attribute write/writeline. Here it the code snippet:
# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess
x = raw_input("Enter the full path + file name + file extension you wish to use: ")
def ripple(x):
with open(x) as file:
for line in file:
for word in line.split():
if ':' in word:
try:
print word.split(':')[-1]
except (IndexError):
pass
ripple(x)
The code above works perfectly when printing to the screen. However I have spent hours reading Python's documentation and can't seem to find a way to have the results written to a file. I know how to open a file and write to it with writeline, readline, etc, but it doesn't seem to work with strings.
Any suggestions on how to achieve this?
PS: I didn't add the code that caused the write error, because I figured this would be easier to look at.
End of First Post
The Solution - Update:
Managed to get python to extract and save it into another file with the code below.
The Code:
inputFile = open ('c:/folder/Thefile.txt', 'r')
outputFile = open ('c:/folder/ExtractedFile.txt', 'w')
tempStore = outputFile
for line in inputFile:
for word in line.split():
if ':' in word:
splitting = word.split(':')[-1]
tempStore.writelines(splitting +'\n')
print splitting
inputFile.close()
outputFile.close()
Update:
checkout droogans code over mine, it was more efficient.
Try this:
with open('workfile', 'w') as f:
f.write(word.split(':')[-1] + '\n')
If you really want to use the print method, you can:
from __future__ import print_function
print("hi there", file=f)
according to Correct way to write line to file in Python. You should add the __future__ import if you are using python 2, if you are using python 3 it's already there.
I think your question is good, and when you're done, you should head over to code review and get your code looked at for other things I've noticed:
# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess
First off, thanks for putting example file contents at the top of your question.
x = raw_input("Enter the full path + file name + file extension you wish to use: ")
I don't think this part is neccessary. You can just create a better parameter for ripple than x. I think file_loc is a pretty standard one.
def ripple(x):
with open(x) as file:
With open, you are able to mark the operation happening to the file. I also like to name my file object according to its job. In other words, with open(file_loc, 'r') as r: reminds me that r.foo is going to be my file that is being read from.
for line in file:
for word in line.split():
if ':' in word:
First off, your for word in line.split() statement does nothing but put the "Hello:there:buddy" string into a list: ["Hello:there:buddy"]. A better idea would be to pass split an argument, which does more or less what you're trying to do here. For example, "Hello:there:buddy".split(":") would output ['Hello', 'there', 'buddy'], making your search for colons an accomplished task.
try:
print word.split(':')[-1]
except (IndexError):
pass
Another advantage is that you won't need to check for an IndexError, since you'll have, at least, an empty string, which when split, comes back as an empty string. In other words, it'll write nothing for that line.
ripple(x)
For ripple(x), you would instead call ripple('/home/user/sometext.txt').
So, try looking over this, and explore code review. There's a guy named Winston who does really awesome work with Python and self-described newbies. I always pick up new tricks from that guy.
Here is my take on it, re-written out:
import os #for renaming the output file
def ripple(file_loc='/typical/location/while/developing.txt'):
outfile = "output.".join(os.path.basename(file_loc).split('.'))
with open(outfile, 'w') as w:
lines = open(file_loc, 'r').readlines() #everything is one giant list
w.write('\n'.join([line.split(':')[-1] for line in lines]))
ripple()
Try breaking this down, line by line, and changing things around. It's pretty condensed, but once you pick up comprehensions and using lists, it'll be more natural to read code this way.
You are trying to call .write() on a string object.
You either got your arguments mixed up (you'll need to call fileobject.write(yourdata), not yourdata.write(fileobject)) or you accidentally re-used the same variable for both your open destination file object and storing a string.
I'm using a text file to store the weight of a neural network that I'm making, but I'm having serious trouble editing the weights stored in this text field. Essentially, I am making a file with a very regular format: Word + \t + Weight + \n, I then use the follow code to run through this text file and grab the parts:
with open(Neuron_File, 'r+') as Original_Neurons:
for Neuron in Original_Neurons:
Word_Stem = re.sub(r'^([a-z-]*)([\t]?)([0-9.]*)(\n)$', r'\1', Neuron)
Weight = float(re.sub(r'^([a-z-]*)([\t]?)([0-9.]*)(\n)$', r'\3', Neuron))
Which is working, however I would then like to be able to change the value of Weight, and write it back to the same text file in the same place. I have managed to successfully create a new file that is modified in the way that I would like, however I am having a strange problem with writing it back to the original file. I am using the below code for it:
def Replace(New_File, Old_File):
for line in open(New_File):
open(Old_File, 'w').write(str(line))
But for some reason this function simply breaks at a certain point in the file. The first 80% transfers fine, but then it cuts the file off at a seemingly random point in the middle of a line. Any ideas? I know there are other questions that are on similar topics, but none of them seem applicable to my situation, and I can't find any mention of another error like the one I'm getting.
Problem is navigable, but my primary interest is in what the origin of this error was. I've never seen anything like it and it intrigued me, as I had no idea what was going on, hoping someone on here would have more of an idea.
with open('input.txt') as in_file:
with open('output.txt', 'w') as out_file:
for line in in_file.readlines():
word, weight = line.split()[:2]
out_file.write('%s\t%s' % (word, float(weight) * 2))
with-block automaticaly closes opened files
You need to close the file handle for the file you're writing.
def Replace(New_File, Old_File):
Old_File_Handle = open(Old_File, 'w')
for line in open(New_File):
Old_File_Handle.write(str(line))
Old_File_Handle.close()
Alternately, use the with statement.
Alternatively, you can just use something like shelve to handle this for you.
def Replace(New_File, Old_File):
for line in open(New_File):
# next line REWRITES outfile EVERY TIME!!!
open(Old_File, 'w').write(str(line))
Result: Old_File will contain ONLY LAST line
Correct implementation:
def Replace(New_File, Old_File):
# open files
inp = open(New_File)
out = open(Old_File, 'w')
for line in inp:
out.write(line)
# close files
out.close()
inp.close()