replacing text in a file, Python - python

so this piece of code is meant to take a line from a file and replace the certain line from the string with a new word/number, but it doesn't seem to work :(
else:
with open('newfile', 'r+')as myfile:
x=input("what would you like to change: \nname \ncolour \nnumber \nenter option:")
if x == "name":
print("your current name is:")
test_lines = myfile.readlines()
print(test_lines[0])
y=input("change name to:")
content = (y)
myfile.write(str.replace((test_lines[0]), str(content)))
I get the error message TypeError: replace() takes at least 2 arguments (1 given), i don't know why (content) is not accepted as an argument. This also happens for the code below
if x == "number":
print ("your current fav. number is:")
test_lines = myfile.readlines()
print(test_lines[2])
number=(int(input("times fav number by a number to get your new number \ne.g 5*2 = 10 \nnew number:")))
result = (int(test_lines[2])*(number))
print (result)
myfile.write(str.replace((test_lines[2]), str(result)))
f=open('newfile', 'r')
print("now we will print the file:")
for line in f:
print (line)
f.close

replace is a function of a 'str' object.
Sounds like you want to do something like (this is a guess not knowing your inputs)
test_lines[0].replace(test_lines[0],str(content))
I'm not sure what you're attempting to accomplish with the logic in there. looks like you want to remove that line completely and replace it?
also i'm unsure what you are trying to do with
content = (y)
the output of input is a str (which is what you want)
EDIT:
In your specific case (replacing a whole line) i would suggest just reassigning that item in the list. e.g.
test_lines[0] = content
To overwrite the file you will have to truncate it to avoid any race conditions. So once you have made your changes in memory, you should seek to the beginning, and rewrite everything.
# Your logic for replacing the line or desired changes
myfile.seek(0)
for l in test_lines:
myfile.write("%s\n" % l)
myfile.truncate()

Try this:
test_lines = myfile.readlines()
print(test_lines[0])
y = input("change name to:")
content = str(y)
myfile.write(test_lines[0].replace(test_lines[0], content))
You have no object known purely as str. The method replace() must be called on a string object. You can call it on test_lines[0] which refers to a string object.
However, you may need to change your actual program flow. However, this should circumvent the error.

You need to call it as test_lines[0].replace(test_lines[0],str(content))
Calling help(str.replace) at the interpreter.
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
Couldn't find the docs.

Related

What causes this return() to create a SyntaxError?

I need this program to create a sheet as a list of strings of ' ' chars and distribute text strings (from a list) into it. I have already coded return statements in python 3 but this one keeps giving
return(riplns)
^
SyntaxError: invalid syntax
It's the return(riplns) on line 39. I want the function to create a number of random numbers (randint) inside a range built around another randint, coming from the function ripimg() that calls this one.
I see clearly where the program declares the list I want this return() to give me. I know its type. I see where I feed variables (of the int type) to it, through .append(). I know from internet research that SyntaxErrors on python's return() functions usually come from mistype but it doesn't seem the case.
#loads the asciified image ("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
#creates a sheet "foglio1", same number of lines as the asciified image, and distributes text on it on a randomised line
#create the sheet foglio1
def create():
ref = open("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
charcount = ""
field = []
for line in ref:
for c in line:
if c != '\n':
charcount += ' '
if c == '\n':
charcount += '*' #<--- YOU GONNA NEED TO MAKE THIS A SPACE IN A FOLLOWING FUNCTION IN THE WRITER.PY PROGRAM
for i in range(50):#<------- VALUE ADJUSTMENT FROM WRITER.PY GOES HERE(default : 50):
charcount += ' '
charcount += '\n'
break
for line in ref:
field.append(charcount)
return(field)
#turn text in a list of lines and trasforms the lines in a list of strings
def poemln():
txt = open("/home/gcg/Documents/Programmazione/Python projects/imgascii/writer/poem")
arrays = []
for line in txt:
arrays.append(line)
txt.close()
return(arrays)
#rander is to be called in ripimg()
def rander(rando, fldepth):
riplns = []
for i in range(fldepth):
riplns.append(randint((rando)-1,(rando)+1)
return(riplns) #<---- THIS RETURN GIVES SyntaxError upon execution
#opens a rip on the side of the image.
def ripimg():
upmost = randint(160, 168)
positions = []
fldepth = 52 #<-----value is manually input as in DISTRIB function.
positions = rander(upmost,fldepth)
return(positions)
I omitted the rest of the program, I believe these functions are enough to get the idea, please tell me if I need to add more.
You have incomplete set of previous line's parenthesis .
In this line:-
riplns.append(randint((rando)-1,(rando)+1)
You have to add one more brace at the end. This was causing error because python was reading things continuously and thought return statement to be a part of previous uncompleted line.

Error in string index out of range: maf file to fasta file

Context: I am trying to convert a maf file (multiple alignment file) to individual fasta file. I keep running into the same error that I'm not sure how to fix and this may be because I'm relatively new to python. My code is below:
open_file = open('C:/Users/Danielle/Desktop/Maf_file.maf','r')
for record in open_file:
print(record[2:7])
if (record[2] == 'Z'):
new_file = open(record[2:7]+".fasta",'w')
header = ">"+record[2:7]+"\n"
sequence = record[46:len(record)]
new_file.write(header)
new_file.write(sequence)
new_file.close()
else:
print("Not correct isolate.")
open_file.close()
The error I get is:
IndexError
Traceback (most recent call last)
2 for record in open_file:
3 print(record[2:7])
----> 4 if (record[2] == 'Z'):
5 new_file = open(record[2:7]+".fasta",'w')
6 header = ">"+record[2:7]+"\n"
IndexError: string index out of range
If I remove the if, else statement it works as I expect but I would like to filter for specific species that start with the character Z.
If anyone could help explain why I can't select for only strings that start with the character Z this way, that would be great! Thanks in advance.
Its giving an error when the length of record is less than 2.
To fix this you can change your if statement to:
if (len(record) > 2 and record[2] == 'Z'):
Ideally you should also handle such cases before separately.
Here's an alternative answer.
The problem you're having is because the record you're reading might not have at least 3 chars. For that reason you have to check the length of the string before checking index 2. As you might have noticed, the line 3 doesn't crash.
Slice operator in short will slice from index 2 to 7 returning anything it finds.
So if you have let look at this:
"abcd"[1:] == "bcd"
"abcd"[1:3] == "bc"
"abcd"[1:10] == "bcd"
"abcd"[4:] == ""
As you can see, it will return anything from index 1 to index 2 excluded. When it doesn't find anything the slice operation stop and return.
So one different way to get the same result as checking for the length would be to do this:
if (record[2:3] == 'Z'):
This way, you're slicing the char at index 2, if the index exists it will return a char otherwise an empty string. That said, I can't say if the slice operation will be faster than checking the length of the string and getting the index then. In some ways, the slice operation does that internally most probably.
A better answer
This way, we can fix the problem you had and also make it a bit more efficient. You're slicing multiple time the record for [2:7] you should store that in a variable. If the index 2 isn't present in the resulting filename, we can assume the filename is empty. If the filename is empty it will be falsy, if not we can check index 0 because it's certainly will be there and index 0 of filename is index 2 of record.
Second problem is to use the format string instead of + operator. It will convert anything you pass to the format string to a string as the format passed is %s. If you'd pass a False or None value, the program will crash as arithmetic operation are only allowed for str + str.
open_file = open('C:/Users/Danielle/Desktop/Maf_file.maf','r')
for record in open_file:
filename = record[2:7]
print(filename)
if (filename and filename[0] == 'Z'):
with open("%s.fasta" % filename,'w') as newfile:
header = ">%s\n" % filename
sequence = record[46:len(record)]
new_file.write(header)
new_file.write(sequence)
else:
print("Not correct isolate.")
open_file.close()
A bit of reformat and we'd end up with this:
def write_fasta(record):
filename = record[2:7]
print(filename)
if (filename and filename[0] == 'Z'):
with open("%s.fasta" % filename,'w') as new_file:
header = ">%s\n" % filename
sequence = record[46:len(record)]
new_file.write(header)
new_file.write(sequence)
else:
print("Not correct isolate.")
maf_filename = 'C:/Users/Danielle/Desktop/Maf_file.maf'
with open(maf_filename, 'r') as maf:
for record in maf:
write_fasta(record)
Use the context manager whenever possible as they'll handle the file closing themselves. So no need to explicitly call the close() method.

How to use "def" with strings

I'm relatively new to programming so I just recently got started with experimenting with "def" in python. This is my code and its keeps on telling me the first name hasn't been defined.
def name(first, last):
first = str(first)
last = str(last)
first = first.upper
last = last,upper
print("HELLO", first, last)
I then run the program and i write a name like
name(bob, robert)
and then it would tell me that "bob" hasn't been defined
You should quote them (using ' or ") if you mean string literals:
name('bob', 'robert')
Beside that, the code need a fix.
def name(first, last):
first = str(first)
last = str(last)
first = first.upper() # Append `()` to call `upper` method.
last = last.upper() # Replaced `,` with `.`.
print("HELLO", first, last)
There's a difference between a variable and a string. A variable is a slot in memory already allocated with a data (string, number, structure...) When you write robert without quotes, Python will search this variable already instancied with this name.
Here it doesn't exists, since you don't write robert = 'something'. If you want to pass a string directly, you just have to write it, surronding by quotes (or triple quotes if it's on multiple lines).
What you want to achieve is calling your name function like this:
def name(first, last):
first = str(first)
last = str(last)
first = first.upper
last = last,upper
print("HELLO %s %s" % (first, last))
name('bob', 'robert') # Will print "HELLO bob robert"
def name(first, last):
first = str(first)
last = str(last)
first = first.upper()
last = last.upper()
print("HELLO", first, last)
name("bob","robert")
1.str-objects has upper-method, but to call it and get result u have to add "()" after the name of method - because you get link to object-method - not to string in upper case...
2.in calling name(bob,robert) - you put the arguments, which are undefined variables..
to do this u have to define these variables before calling, f.g:
bob = "bob"
robert="robert"
name(bob,robert)
You need to put the strings to quotes (either "bob" or 'bob').
So your call would be
name('bob', 'robert')
instead of
name(bob, robert)
.
If you use it without the quotes, python tries to find a variable with a name bob.
Also, you do not need to use the str(first) or str(last) since both are already strings.

How can i write this function that mostly prints to a file?

So I posted about another part of this code yesterday but I've run into another problem. I made a character generator for an RPG and im trying to get the program the output of a character sheet function to a .txt file, but i think whats happening is that the function may return a Nonevalue for some of the stats (which is totally normal,) and then i get an error because of that when i try to write to a .txt file. I'm totally stumped, and help would be vastly appreciated!
# Character Sheet Function.
def char_shee():
print "Name:", name
print "Class:", character_class
print "Class Powers:", class_power
print "Alignment:", alignment
print "Power:", pow, pow_mod()
print "Intelligence:", iq, iq_mod()
print "Agility:", agi, agi_mod()
print "Constitution:", con, con_mod()
print "Cynicism:", cyn, cyn_mod()
print "Charisma:", cha, cha_mod()
print "All Characters Start With 3 Hit Dice"
print"""
\t\t{0}'s History
\t\t------------------
\t\tAge:{1}
\t\t{2}
\t\t{3}
\t\t{4}
\t\t{5}
\t\t{6}
\t\t{7}
\t\t{8}
\t\t{9}
\t\tGeneral Disposition: {10}
\t\tMost important thing is: {11}
\t\tWho is to blame for worlds problems: {12}
\t\tHow to solve the worlds problems: {13}
""".format(name, age, gender_id, ethnic_pr, fcd, wg, fogo_fuck, cur_fam,fam_fuk, nat_nur, gen_dis, wha_wor, who_pro, how_pro)
char_shee()
print "Press enter to continue"
raw_input()
# Export to text file?
print """Just because I like you, let me know if you want this character
saved to a text file. Please remember if you save your character not to
name it after something important, or you might lose it.
"""
text_file = raw_input("Please type 'y' or 'n', if you want a .txt file")
if text_file == "y":
filename = raw_input("\nWhat are we calling your file, include .txt")
target = open(filename, 'w')
target.write(char_shee()
target.close
print "\nOk I created your file."
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
else:
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
EDIT: Here is the output i get:
> Please type 'y' or 'n', if you want a .txt filey
>
> What are we calling your file, include .txt123.txt <function char_shee
> at 0x2ba470> Traceback (most recent call last): File "cncg.py", line
> 595, in <module>
> target.write(pprint(char_shee)) TypeError: must be string or read-only character buffer, not None
Using print writes to sys.stdout, it doesn't return a value.
You you want char_shee to return the character sheet string to write it to a file, you'll need to just build that string instead.
To ease building the string, use a list to collect your strings:
def char_shee():
sheet = []
sheet.append("Name: " + name)
sheet.append("Class: " + character_class)
# ... more appends ...
# Return the string with newlines
return '\n'.join(sheet)
you forgot parenthesis here:
target.write(char_shee())
target.close()
and as #Martijn Pieters pointed out you should return value from char_shee(), instead of printing them.

python write can take 2 arguments

I have a question to make an "output.txt".
I would like to write both word and prob(l.19) results into
an "output.txt" file.
When I write "model_file.write(word, prob)", the terminal scolds me with
"TypeError: function takes exactly 1 argument (2 given)" message.
I tried to add more arguments but it didn't work..
Could anybody help me with my question??
THIS IS A WORD COUNT.PY
total_count = 0
train_file = open(sys.argv[1],"r")
for line in train_file:
words = line.strip().split(" ")
words.append("</s>")
for word in words:t
counts[word] = counts.get(word, 0) + 1
total_count = total_count + 1
model_file = open('output.txt',"w")
for word, count in sorted(counts.items(),reverse=True):
prob = counts[word]*1.0/total_count
print "%s --> %f" % (word, prob)
model_file.write(word, prob)
model_file.close()
#
Just simply replace
model_file.write(word, prob)
with
model_file.write(word+' '+str(prob)+'\n')
Be aware that the method write() was implemented to take only one string argument, so you have to convert prob into a string (by the method str()) and then combine it with word by the string operator +, so that you got only one string argument.
P.S.: though you didn't ask this, I have to say that if you are going to write each word and its probability, you should put model_file.write(word+' '+str(prob)+'\n') into the for statement. Otherwise, if you resist to call it outside of the for statement for some purpose, then you should assign word and prob outside of the for statement too. Or it would cause another error.
You could use the print statement to do this:
print >>model_file, word, prob
I wanna to created a kind on description about my df so I write this:
# Create an empty txt
f = open(os.path.join(pathlib.Path().absolute(),'folder','florder','name.txt'), "a")
# Create an kind of header
f.write('text'+'\n')
f.write('text'+'\n')
f.write("""
-------------------
""")
f.write('text:'+ '\n')
f.write("""
""")
for c in range(0, len(df.columns)):
campo = df.columns[c]
if df[df.columns[c]].dtype== 'object':
text= 'Tex'
outfile = open('name.txt','w')
f.write('str:'+"'"+str(xxx)+"'"'\n')
f.write('str:'+ str(str)+'\n')
f.write('\n')
f.close()

Categories