I am not sure why my computer keeps crashing when using this program I tried editing it by closing the file each time I run but it still crashes.
f = open("testfile.txt", "r")
text = f.read()
text = str(text)
looper= text.count(",")
f.close()
god= open("dog.txt","w+")
god.write("Passwords")
god.close()
block=""
for count in range(looper):
first= (text.find(','))
second= (text.find(':'))
block = text[first:second]
text = text[:first] + text[second:]
god= open("dog.txt","a")
god.write(block)
god.close()
I am trying to take items from a text file and format them into a new text file.
EDITED CODE:
f = open("testfile.txt", "r")
text = f.read()
text = str(text)
looper= text.count(",")
f.close()
god= open("dog.txt","w+")
god.write("Testing")
god.close()
for count in range(looper):
block = ""
first= (text.find(':'))
second= (text.find(','))
block= text[first:second]
text = text[second:]
text = text[first:]
print (block)
god= open("dog.txt","a")
god.write(block)
god.close()
In the first section of code I didn't have the string block clearing and I didn't have the string text updating so what would happen is that each time it looped block would duplicate it self
EX:
loop1) :helloworld
loop2) :helloworld:helloworld
loop3) :helloworld:helloworld:helloworld
making those two changes fixed the problem.
Related
import os, re
config_file = "jsm_gyro_config.txt"
#fptr = open(config, "w")
#text = "demo text"
#fptr.write(text)
#fptr.close()
file = open(config_file, 'r')
file-read = file.read()
for line in file-read:
if re.search(userinput, file-read):
x = re.search(userinput, file-read)
# iteminputted is what the user wants to replace
iteminputted = "ref"
startpostion = x.span[1] + 3
endpostion = startposition + len(iteminputted)
# Find out how to write to a specific location in a file that will finish this off
else:
print("Item not found")
This is what i've tried and here is my thought process as always any help is appreatated and please make it understandable for an idiot :(
To begin with, you should not use - in your variable declarations as it is actually an operator and will always be treated as such. It will attempt to subtract.
Here is the same code with that fixed and also with the input
import os, re
config_file = "jsm_gyro_config.txt"
#fptr = open(config, "w")
#text = "demo text"
#fptr.write(text)
#fptr.close()
file = open(config_file, 'r')
file_read = file.read()
file.close() # You should always close your files.
for line in file_read:
if re.search(userinput, file_read):
x = re.search(userinput, file_read)
# iteminputted is what the user wants to replace
iteminputted = input("Input what you would like to replace > ")
startpostion = x.span[1] + 3
endpostion = startposition + len(iteminputted)
# Find out how to write to a specific location in a file that will finish this off
else:
print("Item not found")
However your question is very unclear, I did the best I could.
I wrote some code to let me type special characters without learning the commands for them so I wrote this:
file = open('test.txt', 'r+')
text = file.read()
text = text.replace('//a', 'Ä')
text = text.replace('//o', 'Ö')
text = text.replace('//u', 'Ü')
text = text.replace('/a', 'ä')
text = text.replace('/o', 'ö')
text = text.replace('/u', 'ü')
text = text.replace('/s', 'ß')
file.truncate(0) # Clears the file
file.write(text.strip()) # edit was .strip(''), made no diffence
print(text)
An example input would be 'n/achtes' which would become 'nächtes'
This sort of works but when I run the file I get a huge amount of blank space in the text file for example 'n/achtes' turns into:
' nächtes'
If I run the program a second time the output, on sublimetext 3, ends with nächtes but has 8 uncopyable copies of <0x00> in a different colour. The amount of blank spaces increases as well in the text file.
truncate(0) resizes the file to zero size, but the current position is not changed.
When writing the data, it is written at current position, so the rest of the file gets null bytes to "pad".
It is a better practice to use truncate() without parameter to truncate the file in the current position:
f.seek(0) # go to the beginning of the file
f.truncate() # truncate in current position
You could try to open the file twice, once for reading and once for writing.
filename = 'text.txt'
with open(filename, 'r') as f:
text = f.read()
print('-' * 20)
print('old text:')
print(text)
replacement_list = [
('//a', 'Ä'),
('//o', 'Ö'),
('//u', 'Ü'),
('/a', 'ä'),
('/o', 'ö'),
('/u', 'ü'),
('/s', 'ß'),
]
for s_old, s_new in replacement_list:
text = text.replace(s_old, s_new)
print('-' * 20)
print('new text:')
print(text)
with open(filename, 'w') as f:
f.write(text.strip())
This is the "click me" function which runs when the button on the interface is clicked.
def click_me():
file_name = file_name_entry.get()
the_file_name = str(file_name)
open(the_file_name, "r")
imp_message = file.read(the_file_name)
There is a grey line beneath the_file_name in brackets and when hovered over says: passing str instead of file - is this intentional?
password_output.delete(0.0, END)
password_output.insert(END, imp_message)
The relevant TKInter code is as follows...
file_name_entry = Entry(encrypt_frame, width=20)
file_name_entry.grid(column = 1, row = 1, sticky = W)
Button(encrypt_frame, text= "Submit", command = click_me).grid(column = 2, row = 1)
The error output is:
IOError: Errno22 invalid mode ('r/) or filename ""
Your code is close, but you're trying to read from the file name rather than the opened file object. Change your code to this:
file=open(the_file_name, "r")
imp_message = file.read()
Better yet, use a context manager which will automatically close the file when you're done:
with open(the_file_name, "r") as f:
imp_message = f.read()
The python documentation has a nice tutorial on reading and writing files:
Python 2 - Reading and writing files
Python 3 - Reading and writing files
Unrelated to the actual question, there are a couple problems with your code.
First, there's no need for this statement:
the_file_name = str(file_name)
In this case, file_name is already a string since it is coming from an Entry widget.
Second, the index 0.0 in the statement password_output.delete(0.0, END) is incorrect. Text widget indexes must be strings in the form of <line>.<column>, and lines start at 1 (one). The proper index for the first character is the string "1.0".
Okay, so here's the deal, folks:
I've been experimenting with Python(3.3), trying to create a python program capable of generating random names for weapons in a game and replacing their old names, which are located inside a text file. Here's my function:
def ModifyFile(shareddottxt):
global name
a = open(str(shareddottxt) , 'r')
b = a.read()
namefix1 = '''SWEP.PrintName = "'''
namefix2 = '''" //sgaardname'''
name1 = b.find(namefix1) + len(namefix1)
name2 = b.find(namefix2, name1)
name = name + b[name1:name2] ## We got our weapon's name! Let's add the suffix.
c = open((shareddottxt + ".lua"), 'r+')
for line in b:
c.write(line.replace(name, (name + namesuffix)))
c.close()
a.close
As you can see, I first open my text file to find the weapon's name. After that, I try to create a new file and copy the contents from the old one, while replacing the weapon's name for (name + namesuffix). However, after calling the function, I get nothing. No file whatsoever. And even if I DO add the file to the folder manually, it does not change. At all.
Namesuffix is generated through another function early on. It is saved as a global var.
Also, my text file is huge, but the bit I'm trying to edit is:
SWEP.PrintName = "KI Stinger 9mm" //sgaardname
The expected result:
SWEP.PrintName = "KI Stinger 9mm NAMESUFFIX" //sgaardname
Where did I mess up, guys?
Something like this is more pythonic.
def replace_in_file(filename, oldtext, newtext):
with open(filename, 'r+') as file:
lines = file.read()
new_lines = lines.replace(oldtext, newtext)
file.seek(0)
file.write(new_lines)
If you don't want to replace that file
def replace_in_file(filename, oldtext, newtext):
with open(filename, 'r') as file, open(filename + ".temp", 'w') as temp:
lines = file.read()
new_lines = lines.replace(oldtext, newtext)
temp.write(new_lines)
I created a notepad text document called "connections.txt". I need to have some initial information inside it, several lines of just URLs. Each URL has it's own line. I put that in manually. Then in my program I have a function that checks if a URL is in the file:
def checkfile(string):
datafile = file(f)
for line in datafile:
if string in line:
return True
return False
where f is declared at the beginning of the program:
f = "D:\connections.txt"
Then I tried to write to the document like this:
file = open(f, "w")
if checkfile(user) == False:
usernames.append(user)
file.write("\n")
file.write(user)
file.close()
but it hasn't really been working correctly..I'm not sure what's wrong..am I doing it wrong?
I want the information in the notepad document to stay there ACROSS runs of the program. I want it to build up.
Thanks.
EDIT: I found something wrong... It needs to be file = f, not datafile = file(f)
But the problem is... It clears the text document every time I rerun the program.
f = "D:\connections.txt"
usernames = []
def checkfile(string):
file = f
for line in file:
if string in line:
return True
print "True"
return False
print "False"
file = open(f, "w")
user = "aasdf"
if checkfile(user) == False:
usernames.append(user)
file.write("\n")
file.write(user)
file.close()
I was working with the file command incorrectly...here is the code that works.
f = "D:\connections.txt"
usernames = []
def checkfile(string):
datafile = file(f)
for line in datafile:
if string in line:
print "True"
return True
print "False"
return False
user = "asdf"
if checkfile(user) == False:
usernames.append(user)
with open(f, "a") as myfile:
myfile.write("\n")
myfile.write(user)
The code that checks for a specific URL is ok!
If the problem is not erasing everything:
To write to the document without erasing everything you have to use the .seek() method:
file = open("D:\connections.txt", "w")
# The .seek() method sets the cursor to the wanted position
# seek(offset, [whence]) where:
# offset = 2 is relative to the end of file
# read more here: http://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek
file.seek(2)
file.write("*The URL you want to write*")
Implemented on your code will be something like:
def checkfile(URL):
# your own function as it is...
if checkfile(URL) == False:
file = open("D:\connections.txt", "w")
file.seek(2)
file.write(URL)
file.close()