overwrite words in text file with python - python

I created a text file that contains in the first line a counter of created users and the rest of the lines the text contains user name, password..
for example:
2
username Name Last_name Password
username1 Name Last_name1 Password1
I'm using the following commands:
def SaveDatA(self):
#if self.CheckValid() == False:
#return
with open("data.txt","a") as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
I want to update the counter to the first line

Do you want this?
f1_lines = open('data.txt', 'r').readlines()
with open('data.txt','w') as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
f1_lines[0]=str(self.counter)+'\n'
f.write(''.join(f1_lines))
With readlines() you create a list contain all of lines in the file so you change the first index of that list with f1_lines[0]=str(self.counter)+'\n' then rewrite it in to the file !

After a lot of trials this code work's:
with open("data.txt","a") as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
fileCopy = open('data.txt', 'r').readlines()
fileCopy[0] = fileCopy[0][1:]
with open("data.txt","w") as f:
f.write(str(self.counter)+" ")
f.write("".join(fileCopy))
but maybe there is another better way ?

Related

Python adds a double entry at the end of output file

This is my code to create a hashtag file. The issue is it does not put the # for the first hashtag and at he end it puts a double hashtag like below.
passiveincome, #onlinemarketing, #wahmlife, #cash, #entrepreneurlifestyle, #makemoneyonline, #makemoneyfast, #entrepreneurlifestyle, #mlm, #mlm
How do I get the code to remove the double output and put the # at the beginning?
import random, os, sys
basepath = os.path.dirname(sys.argv[0]) + "/"
outputpath = "C:/Users/matth/OneDrive/Desktop/Create hashtags/"
paragraphsmin = 9
paragraphsmax = 9
sentencemin = 1
sentencemax = 1
keywords = []
for line in open(basepath + "/base.txt", "r"):
keywords.append(line.replace("\n",""))
keywordlist = []
keyword = open(basepath + "/text-original.txt", "r")
for line in keyword:
keywordlist.append(line.replace("\n", "\n"))
def type(name):
value = name[random.randint(0,len(name)-1)]
return value
"""
def xyz(num):
s1 = '' + type(keywordlist).strip()
return eval('s' + str(num))
"""
def s1():
return '' + type(keywordlist).strip()
def randomSentence():
sent = eval("s" + str(random.randint(1,1)) + "()")
return sent
for keyword in keywords:
outputfile = open(outputpath + keyword.replace(" ", " ") + ".txt", "w")
outputfile.write('')
for p in range(1,random.randint(paragraphsmin,paragraphsmax) + 1):
outputfile.write('')
for s in range(1,random.randint(sentencemin,sentencemax) + 1):
sentence = randomSentence()
if str(sentence)[0] == "\"":
outputfile.write("" + str(sentence)[0] + str(sentence)[1] + str(sentence)[2:] + " ")
else:
outputfile.write("" + str(sentence)[0] + str(sentence)[1:] + ", #")
outputfile.write('')
outputfile.write(sentence.replace("", "") + "")
outputfile.close()
Try replacing
outputfile.write("" + str(sentence)[0] + str(sentence)[1:] + ", #")
with
outputfile.write("#" + str(sentence)[0] + str(sentence)[1:] + ", ")

How to select specific data from CSV files and display all the data in that row

I'm trying to make a code that shows all the details of specific students. The code takes an input of gender and their class and then shows all their data. For example, if I input "Male" and "10A", I want the code to give me all the data from the students who are male and in class 10A. All their information is stored in a CSV file (called details). My code so far is:
file = open("details.csv","rt")
gender_input = input("Input gender of students")
class_input = input("Input class of students")
for line in file:
details_of_gender = line.split(",")
details_of_class = line.split(",")
gender = str(details_of_gender[7])
class1 = str(details_of_class[8])
if gender == "Male":
if class1 == "10A":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
if class1 == "10B":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
if gender == "Female":
if class1 == "10A":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
if class1 == "10B":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
Assuming that your program isn't working just because you're using a variable details that you haven't defined before, here's a better way of doing this:
import csv
with open("details.csv", newline="") as infile:
reader = csv.reader(infile) # use the csv module to read a CSV file!
for row in reader:
gender = row[7]
class = row[8]
if gender in ("Male", "Female") and class in ("10A", "10B"):
print(" ".join(row[:6])) # join elements 0-5 with spaces

Multiple else condition in python

I have python script with will read each IP from file and install agent on that IP using password, there are 5-6 passwords and if one password doesn't work it should try with other all passwords one by one.
This is my script:
##Reading values from SucessfullIp.txt
with open('/root/nix_bsd_mac_inventory-master/SucessfullIp.txt') as f:
ips = set(line.rstrip() for line in f)
##Reading Unique Ip's values
with open("/root/nix_bsd_mac_inventory-master/Unique.txt") as fp:
for line in fp:
line = line.rstrip()
## Comparing unique ip's if ip is already has scanned
if line in ips:
print('{}: Ip is Already Tried: '.format(line))
else:
##Creating inventory.cfg file on the fly for each ip
f3 = open("/root/nix_bsd_mac_inventory-master/inventory.cfg", "w")
print "Processing Ip: " + line
f3.write("[device42_access]" + "\n" +
"base_url = https://1.8.0.3" + "\n" +
"username = uname" + "\n" +
"secret = abcd" + "\n" +
"[discover]" + "\n" +
"cpu= true" + "\n" +
"hardware = true" + "\n" +
"memory = true" + "\n" +
"[access]"+ "\n" +
"credentials = username:passowrd1" + "\n" + ##here we are giving credentials and we have 5-6 passwords
f3.close()
p = subprocess.Popen(["./d42_linux_autodisc_v620"], stdout=subprocess.PIPE) ##This script will require inventory.cfg file created above
p1 = str(p.communicate())
if '1 devices were successfully added/updated' in p1:
print ('Sucessfull Completed Ip: ' +line)
f6 = open("/root/nix_bsd_mac_inventory-master/SucessfullIp.txt","a")
f6.write("\n"+line)
f6.close()
else:
print "Unsuccessfull"
##here want it to check it with other passwords as well
You should iterate over a list of your passwords and break out of the loop if one is successful.
You had a syntax error in the following snippet:
"credentials = username:passowrd1" + "\n" +
This should not end with a + as you are not concatenating anything else to the string.
It will be useful for you to look up break, continue, and else statements that you can use with loops as I have used them in the answer.
I have removed all of your comments, and added comments of my own to explain the logic.
with open("/root/nix_bsd_mac_inventory-master/Unique.txt") as fp:
for line in fp:
line = line.rstrip()
if line in ips:
print('{}: Ip is Already Tried: '.format(line))
continue # Continue means it will skip to the next password
passwords = ['password1', 'password2', 'password3']
for password in passwords:
f3 = open("/root/nix_bsd_mac_inventory-master/inventory.cfg",
"w")
print "Processing Ip: " + line
f3.write("[device42_access]" + "\n" +
"base_url = https://1.8.0.3" + "\n" +
"username = uname" + "\n" +
"secret = abcd" + "\n" +
"[discover]" + "\n" +
"cpu= true" + "\n" +
"hardware = true" + "\n" +
"memory = true" + "\n" +
"[access]" + "\n" +
"credentials = username:" + password + "\n" # Fixed typo here
f3.close()
p = subprocess.Popen(["./d42_linux_autodisc_v620"],
stdout=subprocess.PIPE)
p1 = str(p.communicate())
if '1 devices were successfully added/updated' in p1:
print('Sucessfull Completed Ip: ' + line)
f6 = open("/root/nix_bsd_mac_inventory-master/SucessfullIp.txt", "a")
f6.write("\n" + line)
f6.close()
break # If successful it breaks, so don't need an else
print "Password %s Unsuccessfull" % password
else:
# This happens when there are no more passwords to attempt
print "No passwords were successful"
You can do it using a for loop and a single else:
for password in list_of_password:
...
"credentials = username:" + password + "\n"
...
if '1 devices were successfully added/updated' in p1:
...
break
else:
print "Unsuccessfull"

Python Reading and using data from file

I am currently trying to save scores from a quiz to an excel sheet which allows the user to read the files, but how can I use their save data to only save the last 3 scores of a user. I understand this would mean reading from the file to see the scores and then making it read how many tries the user has had etc. but I can't quite figure out how to make it so the program will only save the last 3 scores from that user or their 3 highest scores. Thank you.
if pclass == 1:
inFile = open("ascores.csv", 'a')
inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
inFile.close()
inFile = open("ascores.csv", 'r')
print(inFile.read())
elif pclass == 2:
inFile = open("bscores.csv", 'a')
inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
inFile.close()
inFile = open("bscores.csv", 'r')
print(inFile.read())
elif pclass == 3:
inFile = open("cscores.csv", 'a')
inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
inFile.close()
inFile = open("cscores.csv", 'r')
print(inFile.read(sorted(reader, key=lambda row: int(row[0]))))
else:
print("Sorry we can not save your data as the class you entered is 1, 2 or 3.")
You are closing the file before reading its contents.
if pclass == 1:
inFile = open("ascores.csv", 'a')
inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
content = inFile.read()
inFile.close()
inFile = open("ascores.csv", 'r')
print(content)
or more concise:
if pclass == 1:
new_score = "\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1))
with open("ascores.csv", 'a') as in_file:
in_file.write(new_score)
content = in_file.read()
print(content)
Using the with statement will close the file for you.
You can edit the long new_score = "\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)) to:
new_score = "\n {}, {}, {:.1f}".format(pname, correct, etime)
see: https://docs.python.org/3.4/library/string.html#format-specification-mini-language for an explanation about string formatting.
You could also simplify your code (never repeat yourself):
def saveScore(pname, correct, etime, pclass):
score_files = {1:"ascores.csv", 2:"bscores.csv", 3:"cscores.csv"}
try:
filename = score_files[pclass]
new_score = "\n {}, {}, {:.1f}".format(pname, correct, etime)
with open(filename, 'a') as in_file:
in_file.write(new_score)
content = in_file.read()
return content
except KeyError:
return None
print(saveScore(pname, correct, etime, pclass))

Python Nested Loop Fails

I am writing a program to perform file integrity checks of files in a directory. There are 3 nested loops in the code. When I run the code, the first two loops work great but the third loop does not run more than once.
import hashlib
import logging as log
import optparse
import os
import re
import sys
import glob
import shutil
def md5(fileName):
"""Compute md5 hash of the specified file"""
try:
fileHandle = open(fileName, "rb")
except IOError:
return
m5Hash = hashlib.md5()
while True:
data = fileHandle.read(8192)
if not data:
break
m5Hash.update(data)
fileHandle.close()
return m5Hash.hexdigest()
req = open("requested.txt")
for reqline in req:
reqName = reqline[reqline.rfind('/') + 1:len(reqline) - 1]
reqDir = reqline[0:reqline.rfind('/') + 1]
ezfimlog = open("ezfimlog.txt", 'a')
actFile = open("activefile.txt")
tempFile = open("activetemp.txt", 'w')
for name in glob.glob(reqDir + reqName):
fileHash = md5(name)
actInt = 0
if fileHash != None:
print fileHash
for actLine in actFile:
actNameDir = actLine[0:actLine.rfind(' : ')]
actHash = actLine[actLine.rfind(' : ') + 3:len(actLine) -1]
print (name + " " + actHash + " " + fileHash)
if actNameDir == name and actHash == fileHash:
tempFile.write(name + " : " + fileHash + "\n")
actInt = 1
if actNameDir == name and actHash != fileHash:
tempFile.write(name + " : " + actHash + "\n")
actInt = 1
ezfimlog.write("EzFIM Log: The file " + name + " was modified: " + actHash + "\n")
if actInt == 0:
ezfimlog.write("EzFIM Log: The file " + name + " was created: " + fileHash + "\n")
tempFile.write(name + " : " + fileHash + "\n")
shutil.copyfile("activetemp.txt", "activefile.txt")
You open actFile once and then try to read it many times. You'll need to open it each time you want to read it.
Move this line:
actFile = open("activefile.txt")
to just before this line:
for actLine in actFile:

Categories