The user gives input to the program and it should write it in a file There is a problem with uploading it to the txt file.
Plan = open("Plan.txt", "r")
content = Plan.read()
Plan_lista = content.split(",")
Przedmioty = []
Przedmioty = list(set(Plan_lista))
Przedmioty.remove("")
Plan.close()
#Dodawanie linków do listy
Linki = open("Linki.txt", "w+")
print("\n" + "Podaj Link do:")
a=0;
for i in range(len(Przedmioty)):
print (Przedmioty[a], end = "\r")
link = input(": ")
Linki.write(Przedmioty[a] + "," + link)
if ( a != len(Przedmioty)-1):
Linki.write(", ")
a+=1
Related
I would like to count or add numbers to the file everytime I add something to it.
My file is consist of
Account|Username|Password
I would like to have it like this whenever the user adds another account.
# Account Username Password
1 Facebook Name Pass
My code of adding account is this
def add_account():
acc = input("Enter the name of your account.")
username = input(f"Enter the username of your {acc}")
password = input(f"Enter the password of your {acc}")
ask = input(f" Do you like to save {acc} credentials? Y|N")
if ask == "Y":
with open("myfile.txt", "a") as file:
file.write("" + "|" + acc + "|" + username + "|" + password)
file.close()
add_accout()
def view_account():
file = open("myfile.txt", "r")
line = file.readline()
for line in file:
a, b, c, d = line.split("|")
d = d.strip()
print(formatStr(a), formatStr(b), formatStr(c), formatStr(d))
view_account()
def formatStr(str):
nochars = 15
return str + (" "*(nochars - len(str))
How can I count the appended lines?
As jarmod is suggesting in the comments, you can use a global counting variable to number each added account:
counting = 0
def add_account():
global counting
acc = input("Enter the name of your account.")
username = input(f"Enter the username of your {acc}")
password = input(f"Enter the password of your {acc}")
ask = input(f" Do you like to save {acc} credentials? Y|N")
if ask == "Y":
counting += 1
with open("myfile.txt", "a") as file:
file.write("" + acc + username + password + str(counting))
file.close()
add_account()
If you need to be able to quit the program, restart it later, and have it discover the last account number stored in your database, then you can do this as follows to calculate the next free account number:
SEPARATOR = '|'
def next_account_number():
next_num = 1
with open("myfile.txt", "r") as f:
# Read lines discarding empty lines
lines = f.read().splitlines()
lines = list(filter(lambda x: x != "", lines))
if len(lines) > 1:
account = lines[-1].split(SEPARATOR)
try:
next_num = int(account[0]) + 1
except ValueError:
pass
return next_num
print("Next account number:", next_account_number())
I am trying to append the parameters passed to a function to a specific place in an existing text file.
txt file:
query{
text:"",
source_language:"",
target_language:"",
},
data_type:[16],
params{
client:"xyz"
}
python:
def function(text,source_language,target_language):
f = open("file.txt", "w");
f.write( 'text:' + text + '\n' )
f.write( 'source_language:' + source_language + '\n' )
f.write( 'target_language:' + target_language + '\n' )
f.close()
But, its not working. Is there a way to append the parameters directly into the file including " " and ,. I am trying to add just the parameters into the existing file with data at the specified position.
Solution
In revision to your comments, considering that this is only being applied to the example above and need only to alter those specific three lines, this will accomplish the task (included if location: in case you don't match keyword it won't erase your file by open('w')
def change_text(new_text):
content[1] = list(content[1])
y = list(new_text)
content[1] = content[1][:6] + y + content[1][-2:]
content[1] = ''.join(content[1])
def change_source_l(new_source_l):
content[2] = list(content[2])
y = list(new_source_l)
content[2] = content[2][:17] + y + content[2][-2:]
content[2] = ''.join(content[2])
def change_target_l(new_target_l):
content[3] = list(content[3])
y = list(new_target_l)
content[3] = content[3][:17] + y + content[3][-2:]
content[3] = ''.join(content[3])
filename = open('query.txt', 'r')
content = filename.read()
content = content.split()
filename.close()
name = open('query.txt', 'w')
change_text('something')
change_source_l('this')
change_target_l('that')
name.write('\n'.join(content))
name.close()
Output
(xenial)vash#localhost:~/python/LPTHW$ cat query.txt
query{
text:"something",
source_language:"this",
target_language:"that",
},
data_type:[16],
params{
client:"xyz"
Open file in r+ mode
Use .seek method from Python file I/O and then write your content.
I'm currently working on a task where I must store scores in a text file. This is my code thus far:
def FileHandle():
score = str(Name) + ": " + str(correct)
File = open('Test.txt', 'a')
File.write(score)
File.close()
Name = input("Name: ")
correct = input("Number: ")
FileHandle()
My question is, how would I check already existed names in the text file and only add their score, rather than name and score, to the line it existed on?
This is what the file looks like:
Jonathon: 1
Micky: 5
How it would look after adding a score:
Jonathon: 1, 4
Mickey: 5
# The score added here is Jonathon's 4
Attempt:
# Accept scores
name = input("Name: ")
correct = input("Number: ")
if name in grade_book.keys and "," in grade_book.keys <= 2():
grade_book[name] += ',' + correct
else:
grade_book[name] = correct
If you are entering many scores at a time, I suggest reading the file into memory and working with things there. Doing an open/close on the file for every score update is very inefficient.
# Read the file into a dictionary
grade_book = {}
File = open('Test.txt', 'r')
for line in File:
name, scores = line.split(':')
grade_book[name] = scores.strip()
File.close()
print grade_book
# Accept scores
name = raw_input("Name: ")
while name != "":
correct = raw_input("Number: ")
if name in grade_book.keys():
grade_book[name] += ',' + correct
else:
grade_book[name] = correct
name = raw_input("Name: ")
# Write dictionary back to the file
File = open('Test.txt', 'w')
for name, scores in grade_book.items():
out_line = name + ':' + scores + "\n"
File.write(out_line)
File.close()
Unfortunately you would have to go over the file, find the correct line, edit it and write in a temp file and then move that file to original. Best first use a data structure like dict etc. to update scores and finally when done write or persist them.
def filehandle(name,correct):
temp = open('temp', 'wb')
with open('Test.txt', 'r') as f:
for line in f:
if line.startswith(name):
line = line.strip() + correct +'\n'
temp.write(line)
temp.close()
shutils.move('temp', 'data.txt')
You need to pass in the parameters while calling the functions.
Name = input("Name: ")
correct = input("Number: ")
filehandle(name, correct)
Sorry for the Title not sure how to word this.
What i am trying to do is make a code that can be only written and read using my program I have already made it so i can write code out to a file, But i am unsure how to make it be read without changing the text file i only want my code to print out to the console or idle without changing the text file at all, I am not asking you to write out the code for me but just how to go about doing this?
print ("Welcome Who am i speaking too?")
User = input("Name: ")
print ("Welcome " +User)
Running = True
def FileReader():
FileName = input("Please Enter File Name: ")
file = open (FileName + ".txt" , "r")
#How Do i go about this?
print (file.read())
file.close()
def FileOutput():
NameOfFile = input("Enter File Name: ")
File = open(NameOfFile + ".txt", "wt")
Content = input("Type Your Message: ")
Content = Content.replace(" ", "SP")
Content = Content.replace("a", "ASDAFAS")
Content = Content.replace("b", "ASDAKSGDHLHASJD")
Content = Content.replace("c", "ASHJDGASGDKJASG")
Content = Content.replace("d", "JHASGDHASLASHGD")
Content = Content.replace("e", "AKJ:SBDKJASBDASJDBSDBKL")
Content = Content.replace("f", "KBASLLASIBDJBASLDJ")
Content = Content.replace("g", "ASJHDVBLKAJSDBLASJDB")
Content = Content.replace("h", "JHAKSDHKDKSAJDHASJKSHDA")
Content = Content.replace("i", "KJABSDJKABSDKJBASKJDBASKJDB")
Content = Content.replace("j", ":AJSDJASDJKAHSDJHSD")
Content = Content.replace("k", "OAHISDIUHASIDASDHD")
Content = Content.replace("l", "UIAHSDUIHSADIUSHADUIYSA")
Content = Content.replace("m", "ASHDUASHDUHASUDHUIASDHIUHA")
Content = Content.replace("n", "IUAHSDIUHASIDUIAUSHDHUIS")
Content = Content.replace("o", "AHJSVDJHSVABDJHVSD")
Content = Content.replace("p", "IASDIJASIDJAISDJOIAJSD")
Content = Content.replace("q", "LIUAGSDIUGWVDASID")
Content = Content.replace("r", "JAHSDJWIUCBASB")
Content = Content.replace("s", "OIAHSDBIWUBDUIB")
Content = Content.replace("t", "LAJHSBDHBWQIEUBQWIUW")
Content = Content.replace("u", "INQWOIDNWQIOND")
Content = Content.replace("v", "OIHQWEIUCBWOIQBEUWQBEWOQIEB")
Content = Content.replace("W", "OASIHDOIASDOSAHDAISDH")
Content = Content.replace("x", "OIAJDIWQDBUIOEHWQE")
Content = Content.replace("y", "POASJDPOQWEOJWQOEJWQEOP")
Content = Content.replace("z", "ASJDBSOBDOWBQDWIOD")
File.write(Content)
while Running:
What = input("What Would you like to do: ")
if What == "read":
FileReader()
if What == "write":
FileOutput()
if What == "close":
Running = False
Himal is right.
file.read()
file.close()
I'm attempting to login to an Ubuntu server and search logs at several different paths with a function that already works locally (Python 2.7 - win7 machine). Below is the function of how I login and select the logs (also, the basis of my program is Python's cmd module):
def do_siteserver(self, line):
import paramiko
paramiko.util.log_to_file('c:\Python27\paramiko-wininst.log')
host = '10.5.48.65'
portNum = raw_input("\nEnter a port number: ")
while True:
try:
port = int(portNum)
break
except:
print "\nPort is not valid!!!"
break
transport = paramiko.Transport((host,port))
while True:
try:
passW = raw_input("\nEnter the SiteServer weekly password: ")
password = passW
username = 'gilbert'
nport = str(port)
print '\nEstablishing SFTP connection to: {}:{} ...'.format(host,port)
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
print 'Authorization Successful!!!'
log_names = ("/var/log/apache2/access.log",
"/var/log/apache2/error.log",
"/var/opt/smartmerch/log/merch_error.log",
"/var/opt/smartmerch/log/merch_event.log",
"/var/opt/smartmerch/log/server_sync.log")
#call search function here?
#for log_file, local_name in log_names.iteritems():
# sftp.get(log_file, local_name)
#sftp.close()
#transport.close()
break
except:
print "\nAuthorization Failed!!!"
Here is the function (in the same class) that I want to call:
def do_search(self, line):
print '\nCurrent dir: '+ os.getcwd()
userpath = raw_input("\nPlease enter a path to search (only enter folder name, eg. SQA\log): ")
directory = os.path.join("c:\\",userpath)
os.chdir(directory)
print "\n SEARCHES ARE CASE SENSITIVE"
print " "
line = "[1]Single File [2]Multiple Files [3]STATIC HEX"
col1 = line[0:14]
col2 = line[15:32]
col3 = line[33:46]
print " " + col1 + " " + col2 + " " + col3
print "\nCurrent Dir: " + os.getcwd()
searchType = raw_input("\nSelect type of search: ")
if searchType == '1':
logfile = raw_input("\nEnter filename to search (eg. name.log): ")
fiLe = open(logfile, "r")
userString = raw_input("\nEnter a string name to search: ")
for i,line in enumerate(fiLe.readlines()):
if userString in line:
print "String: " + userString
print "File: " + os.join(directory,logfile)
print "Line: " + str(i)
break
else:
print "%s NOT in %s" % (userString, logfile)
fiLe.close()
elif searchType =='2':
print "\nDirectory to be searched: " + directory
#directory = os.path.join("c:\\","SQA_log")
userstring = raw_input("Enter a string name to search: ")
userStrHEX = userstring.encode('hex')
userStrASCII = ''.join(str(ord(char)) for char in userstring)
regex = re.compile(r"(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII )))
choice = raw_input("1: search with respect to whitespace. 2: search ignoring whitespace: ")
if choice == '1':
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(os.path.join(root, file))
for i,line in enumerate(f.readlines()):
result = regex.search(line)
if result:
print "\nLine: " + str(i)
print "File: " + os.path.join(root,file)
print "String Type: " + result.group() + '\n'
f.close()
re.purge()
if choice == '2':
regex2 = re.compile(r'\s+')
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(os.path.join(root, file))
for i,line in enumerate(f.readlines()):
result2 = regex.search(re.sub(regex2, '',line))
if result2:
print "\nLine: " + str(i)
print "File: " + os.path.join(root,file)
print "String Type: " + result2.group() + '\n'
f.close()
re.purge()
elif searchType =='3':
print "\nDirectory to be searched: " + directory
print " "
#directory = os.path.join("c:\\","SQA_log")
regex = re.compile(r'(?:3\d){6}')
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(os.path.join(root,file))
for i, line in enumerate(f.readlines()):
searchedstr = regex.findall(line)
ln = str(i)
for word in searchedstr:
print "\nString found: " + word
print "Line: " + ln
print "File: " + os.path.join(root,file)
print " "
logfile = open('result3.log', 'w')
f.close()
re.purge()
self.do_search(linenumber)
That is all.
Methods are invoked via the object that has them.
self.do_search(...)