I have this code in Python which adds a line to a given file. The problem is that i want to add this blazegraph_address only if there isn't the same line already in the file. If there is, I don't need the address to be added to the file. The function code for this is below:
def write_to_address_file(blazegraph_address):
address_path = open("./saved_info/saved_address.txt", "a")
with open("./saved_info/saved_address.txt") as f:
seen = set()
seen.add(f.read())
print("SEEN",seen)
if blazegraph_address in seen:
print("ADDRESS IN SET ALREADY")
else:
seen.add(blazegraph_address)
address_path.write("\n"+str(blazegraph_address))
The problem is that the set populates with the file contents even though there are duplicates. How to only add to the file if the address is not in the file already?
Your code read the entire file, not line by line.
For this, you need to use create your set with the lines:
Modify:
seen = set()
seen.add(f.read())
With:
seen = set(f.read().split('\n'))
def write_to_address_file(blazegraph_address):
address_path = open("./saved_info/saved_address.txt", "a")
with open("./saved_info/saved_address.txt", "r") as msg:
data = msg.read().splitlines()
if blazegraph_address in data:
print("ADDRESS IN SET ALREADY")
else:
address_path.write("\n"+str(blazegraph_address))
Related
I need to define a fucntion that will, in short:
Open and grab the content from an existing file
Transform that content
Create a new file
Write that new content in this new file
Print the content of the new file
I'm a complete begginer, but I got this until now. How can I improve this?
def text():
#open the existing file
text_file = open('music.txt', 'r')
#reads the file
reading = text_file.read ()
#this turns everything to lower case, counts the words and displays the list vertically
from collections import Counter
new_text = reading.lower()
list_words = Counter(new_text.split())
ordered_list = sorted(list_words.items())
#creates a new file and writes the content there
with open('finheiro_saida.txt', 'x') as final_file:
for i in ordem:
finheiro_saida.write(str(i) + '\n')
#not sure how to open this new file and print its content, when I tried it says the new file doesn't exist in the directory - tried everything.
final = open('C:/Users/maria/OneDrive/Documents/SD_DTM/ficheiro_saida.txt', 'r')
read_file = final.read ()
print(read_file)
You can open the new file and print its content the same way you read and wrote to it!
# ...After all your previous code...
with open('finheiro_saida.txt', 'r') as final_file:
final_file_content = final_file.read()
print(final_file_content)
Fixed some syntax error in your code.
you can display the the same way you read.
Also provide all imports to the start of the file.
you can also read all lines from the file as a list using file.readlines()
from collections import Counter
def text():
# open the existing file
text_file = open("music.txt", "r")
# reads the file
reading = text_file.read()
# this turns everything to lower case, counts the words and displays the list vertically
new_text = reading.lower()
list_words = Counter(new_text.split())
ordered_list = sorted(list_words.items())
# creates a new file and writes the content there
file_name = "finheiro_saida.txt"
with open("finheiro_saida.txt", "x") as final_file:
for i in ordered_list:
final_file.write(str(i) + "\n")
return file_name
def display(final_file_name):
with open(final_file_name) as file:
print(file.read())
final_file_name = text()
display(final_file_name)
Here is the code and I am trying to see what I have done wrong. I am new to python functions and linking external files so it would be nice if you could explain your code.
def get_data(filename):
records = []
with open(filename) as readfile:
lines = readfile.readlines()
for line in lines:
# variable line contains:
str_rec = line.split(",")
pname = str_rec[0]
price = int(str_rec[1])
quantity = int(str_rec[2])
records.append([pname, price, quantity])
#caution: indentation
return records
hell= get_data(data.txt)
print(hell)
data.txt is a link to another file that I am trying to pass as an argument.
open(filename) takes the filename as a string, so you should pass the name as a string, not the actual file.
hell= get_data("data.txt")
I am trying to add a list file to a script.
I need to make it so that to take the public key data from the "list.txt" file and save all the results to the "save.txt" file?
from bitcoinlib.keys import Address
master = Address ("0341b40ab5b2972161f2ff3d5487e0fb8260f2d98221cc2eb4fa3f28b6ad10d81e", encoding = 'bech32', script_type = 'p2wpkh')
print (master.address)
At the moment I am getting one value
bc1q7wdz5dcs553f2y6qgf38xdgqs2kqgkhn5ydn9l
How to fix that in place of this value: 0341b40ab5b2972161f2ff3d5487e0fb8260f2d98221cc2eb4fa3f28b6ad10d81e
There was a list of this file "list.txt"
02485a4e62913be3db116d1ab15f84110599ea8905cd7dbae7be6fa02033fdb54e
0315da5f8f47787f6e8294bd369a4dd81aea97429630ecae831a9f6362a6917106
023741e71ebddc5eca046c9b23ac7c5230160fe1335e655c9bbe0b8a20c8d89802
037782a3fcc6c0ca092658a513c9f051cc95d540d215f0c965176c664d49d3e732
029c6c7748107fc9584a838df6a2c8224ae2339e2a95b15b4cd8bcc67c2d149cd5
To get all the value and save to the file "save.txt"
bc1q6jxrahx3rw6lt2nlv5fpsdtllyzaa03m4d98xv
bc1qct3fu8543tryapkq4kpgw5ph8cj74zhtrdp5sx
bc1q5a3h25vu4kn90sc70rkm65narezzw97khu4dhu
bc1qutzkrtc7tqqjgrzns3s3h92f8wfxvfhp99ppnn
bc1ql2slqxzp7c9hdxhlp0ehlzdg2qa94xh5lk2anw
Please help me with fixing the code!
As far as i'm concerned you want to use each line of file separately.
First read all the lines to list:
with open('list.txt', 'r') as f:
lists = [i.replace('\n', '') for i in f.readlines()]
Then for each line, create Address instance, and save it to another list:
addresses = []
for l in lists:
master = Address(l, encoding = 'bech32', script_type = 'p2wpkh')
addresses.append(master.address)
The last part is to save all to file save.txt
with open('save.txt', 'w+') as f:
for a in addresses:
f.write(a + '\n')
I am running Python 3.5.1
I have a text file that I'm trying to search through and replace or overwrite text if it matches a predefined variable. Below is a simple example:
test2.txt
A Bunch of Nonsense Stuff
############################
# More Stuff Goes HERE #
############################
More stuff here
Outdated line of information that has no comment above - message_label
The last line in this example needs to be overwritten so the new file looks like below:
test2.txt after script
A Bunch of Nonsense Stuff
############################
# More Stuff Goes HERE #
############################
More stuff here
# This is an important line that needs to be copied
Very Important Line of information that the above line is a comment for - message_label
The function I have written idealAppend does not work as intended and subsequent executions create a bit of a mess. My workaround has been to separate the two lines into single line variables but this doesn't scale well. I want to use this function throughout my script with the ability to handle any number of lines. (if that makes sense)
Script
#!/usr/bin/env python3
import sys, fileinput, os
def main():
file = 'test2.txt'
fullData = r'''
# This is an important line that needs to be copied
Very Important Line of information that the above line is a comment for - message_label
'''
idealAppend(file, fullData)
def idealAppend(filename, data):
label = data.split()[-1] # Grab last word of the Append String
for line in fileinput.input(filename, inplace=1, backup='.bak'):
if line.strip().endswith(label) and line != data: # If a line 2 exists that matches the last word (label)
line = data # Overwrite with new line, comment, new line, and append data.
sys.stdout.write(line) # Write changes to current line
with open(filename, 'r+') as file: # Open File with rw permissions
line_found = any(data in line for line in file) # Search if Append exists in file
if not line_found: # If data does NOT exist
file.seek(0, os.SEEK_END) # Goes to last line of the file
file.write(data) # Write data to the end of the file
if __name__ == "__main__": main()
Workaround Script
This seems to work perfectly as long as I only need to write exactly two lines. I'd love this to be more dynamic when it comes to number of lines so I can reuse the function easily.
#!/usr/bin/env python3
import sys, fileinput, os
def main():
file = 'test2.txt'
comment = r'# This is an important line that needs to be copied'
append = r'Very Important Line of information that the above line is a comment for - message_label'
appendFile(file, comment, append)
def appendFile(filename, comment, append):
label = append.split()[-1] # Grab last word of the Append String
for line in fileinput.input(filename, inplace=1, backup='.bak'):
if line.strip().endswith(label) and line != append: # If a line 2 exists that matches the last word (label)
line = '\n' + comment + '\n' + append # Overwrite with new line, comment, new line, and append data.
sys.stdout.write(line) # Write changes to current line
with open(filename, 'r+') as file: # Open File with rw permissions
line_found = any(append in line for line in file) # Search if Append exists in file
if not line_found: # If data does NOT exist
file.seek(0, os.SEEK_END) # Goes to last line of the file
file.write('\n' + comment + '\n' + append) # Write data to the end of the file
if __name__ == "__main__": main()
I am very new to Python so I'm hoping there is a simple solution that I overlooked. I thought it might make sense to try and split the fullData variable at the new line characters into a list or tuple, filter the label from the last item in the list, then output all entries but this is starting to move beyond what I've learned so far.
If I understand your issue correctly, you can just open the input and output files, then check whether the line contains old information and ends with the label and write the appropriate content accordingly.
with open('in.txt') as f, open('out.txt', 'r') as output:
for line in f:
if line.endswith(label) and not line.startswith(new_info):
output.write(replacement_text)
else:
output.write(line)
If you want to update the original file instead of creating a second one, it's easiest to just delete the original and rename the new one instead of trying to modify it in place.
Is this what you are looking for ? It's looking for a label and then replaces the whole line with whatever you want.
test2.txt
A Bunch of Nonsense Stuff
############################
# More Stuff Goes HERE #
############################
More stuff here
Here is to be replaced - to_replace
script.py
#!/usr/bin/env python3
def main():
file = 'test2.txt'
label_to_modify = "to_replace"
replace_with = "# Blabla\nMultiline\nHello"
"""
# Raw string stored in a file
file_replace_with = 'replace_with.txt'
with open(file_replace_with, 'r') as f:
replace_with = f.read()
"""
appendFile(file, label_to_modify, replace_with)
def appendFile(filename, label_to_modify, replace_with):
new_file = []
with open(filename, 'r') as f:
for line in f:
if len(line.split()) > 0 and line.split()[-1] == label_to_modify:
new_file.append(replace_with)
else:
new_file.append(line)
with open(filename + ".bak", 'w') as f:
f.write(''.join(new_file))
if __name__ == "__main__": main()
test2.txt.bak
A Bunch of Nonsense Stuff
############################
# More Stuff Goes HERE #
############################
More stuff here
# Blabla
Multiline
Hello
Reading over both answers I've come up with the following as the best solution i can get to work. It seems to do everything I need. Thanks Everyone.
#!/usr/bin/env python3
def main():
testConfFile = 'test2.txt' # /etc/apache2/apache2.conf
testConfLabel = 'timed_combined'
testConfData = r'''###This is an important line that needs to be copied - ##-#-####
Very Important Line of information that the above line is a \"r\" comment for - message_label'''
testFormatAppend(testConfFile, testConfData, testConfLabel) # Add new test format
def testFormatAppend(filename, data, label):
dataSplit = data.splitlines()
fileDataStr = ''
with open(filename, 'r') as file:
fileData = stringToDictByLine(file)
for key, val in fileData.items():
for row in dataSplit:
if val.strip().endswith(row.strip().split()[-1]):
fileData[key] = ''
fileLen = len(fileData)
if fileData[fileLen] == '':
fileLen += 1
fileData[fileLen] = data
else:
fileLen += 1
fileData[fileLen] = '\n' + data
for key, val in fileData.items():
fileDataStr += val
with open(filename, 'w') as file:
file.writelines(str(fileDataStr))
def stringToDictByLine(data):
fileData = {}
i = 1
for line in data:
fileData[i] = line
i += 1
return fileData
if __name__ == "__main__": main()
Hi I'm new to python. I am trying to add different key value pairs to a dictionary depending on different if statements like the following:
def getContent(file)
for line in file:
content = {}
if line.startswith(titlestart):
line = line.replace(titlestart, "")
line = line.replace("]]></title>", "")
content["title"] = line
elif line.startswith(linkstart):
line = line.replace(linkstart, "")
line = line.replace("]]>", "")
content["link"] = line
elif line.startswith(pubstart):
line = line.replace(pubstart, "")
line = line.replace("</pubdate>", "")
content["pubdate"] = line
return content
print getContent(list)
However, this always returns the empty dictionary {}.
I thought it was variable scope issue at first but that doesn't seem to be it. I feel like this is a very simple question but I'm not sure what to google to find the answer.
Any help would be appreciated.
You reinitialize content for every line, move the initialization outside of the loop:
def getContent(file)
content = {}
for line in file:
etc.