The script is adding a line break right after the curly braces while writing both strings right after the username. I would think this is because of my source text file has encoding in it adding the breaks but as far as I can tell it does not. Am I misunderstanding how write works? Something simple I'm missing. Been looking at this too long and need a new set of eyes.
users_list = []
users = input("File of User's ")
user_file = open(users + '.txt', 'r')
for i in user_file:
users_list.append(i)
sql_file = open('sql.txt', 'w')
sql_file.write("SELECT MACHINE.NAME AS SYSTEM_NAME, SYSTEM_DESCRIPTION,
MACHINE.IP, MACHINE.MAC, MACHINE.ID as TOPIC_ID FROM MACHINE WHERE
((MACHINE.USER_NAME = '{}') OR ".format(users_list[0]))
for i in users_list:
sql_file.write("(MACHINE.USER_NAME = '{}')".format(i))
sql_file.write(" OR ")
The output of the file looks like this:
SELECT MACHINE.NAME AS SYSTEM_NAME, SYSTEM_DESCRIPTION, MACHINE.IP, MACHINE.MAC, MACHINE.ID as TOPIC_ID FROM MACHINE WHERE ((MACHINE.USER_NAME = 'hnelson
') OR (MACHINE.USER_NAME = 'hnelson
') OR (MACHINE.USER_NAME = 'snery
') OR (MACHINE.USER_NAME = 'jherman
change your line 7 and 8
for i in user_file:
users_list.append(i)
to
for i in user_file:
users_list.append(i.strip())
and it should work as expected.
It is because i is a line from user_file and it ends with \n. i.strip() removes the trailing newline.
Related
So I've written a simple program that allows user to enter a line they would like to edit and text they would like to put into that line
def edit_line(file):
a_file = open(file, 'r')
list_of_lines = a_file.readlines()
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'
a_file = open(file, 'w')
a_file.writelines(list_of_lines)
a_file.close()
edit_line('sample.txt')
When I run the program it works fine. However, It asks the user to input the text first and the line number second.
What is the reason for this and how can I fix it?
If you want to fix the problem, just split the one line into two:
Instead of:
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'
Do:
index = int(input('What line would you like to edit?: ')) - 1
list_of_lines[index] = input('Write your text here: ') + '\n'
And as the answer #Guy linked explains, when you are doing an assignment line of code, the right hand (value of the variable) is run before the left side.
Validation is everything! What would happen if the user's input for the line number wasn't within the range of lines read from the file?
Here's a more robust approach:
def edit_line(filename):
with open(filename, 'r+') as file:
lines = file.readlines()
while True:
try:
lineno = int(input('What line would you like to edit: '))
if 0 <= lineno < len(lines):
lines[lineno] = input('Write your text here: ') + '\n'
file.seek(0)
file.writelines(lines)
file.truncate()
break
else:
raise ValueError('Line number out of range')
except ValueError as e:
print(e)
edit_line('edit.txt')
The my_data.txt file looks like this:
jim#gmail.com: hello123
tim#gmail.com: hello1234
The program actually extracts the email address and password from the my_data.txt file really intelligently for a basic programmer at least. But each time I run it, it yells ValueError: substring not found, even thou I tried both the string methods: .index() and .find().
file = open('my_data.txt', 'r')
for line in file.readlines():
break_line = line.index(':') # OR: break_line = line.find(':')
email = line[:break_line]
password = line[(break_line + 2):len(line)]
print(line.find(':'))
I expect you got empty lines in your text file. Try skipping empty lines and lines that do not contain ":" at the beginning:
for line in file.readlines():
if not line.strip():
continue
if ":" not in line:
continue
break_line = line.index(':') # OR: break_line = line.find(':')
email = line[:break_line]
password = line[(break_line + 2):len(line)]
print(line.find(':'))
Maybe you can try this code:
for line in file.readlines():
if line.strip(): # meaning there is a valid line
print(line)
break_line = line.split(':') #index(':') # OR: break_line = line.find(':')
email = break_line[0]
print(email)
password = break_line[1]
print(password)
'''volunteerList.append([ [name], [coinType], [weight], [correct], "\n"])'''
the piece of code above is the code I have tried but the details entered end up on the same line and delete parts of the last set of details entered.
I am not sure where the file is in this example but you would want to do this not to overwrite a file:
name = "A"
coinType = "B"
weight = 99
correct = False
your_list = [ name, coinType, weight, correct]
text = "\n" + " ".join([str(x) for x in your_list])
with open("output.txt", "a") as f:
f.write(text)
So I'm trying to write all this info to a .txt file, but due to the names being pulled from a .txt file that goes
Liam
Noah
William
etc...
When I write to a file, it puts the first and last names on separate lines from everything else.
I've looked on StackOverflow for a solution but I couldn't find anything specific enough.
password = input('Enter the Password you would like to use ')
open('names.txt', 'r+')
lines = open("names.txt").readlines()
firstName = lines[0]
words = firstName.split()
firstNameChoice = random.choice(lines)
open('names.txt', 'r+')
lines = open("names.txt").readlines()
lastName = lines[0]
words = lastName.split()
lastNameChoice = random.choice(lines)
def signUp():
randomNumber = str(random.randint(0,10000))
accountFile = open('accounts.txt', 'a')
accountFile.write(firstNameChoice)
accountFile.write(lastNameChoice)
accountFile.write(randomNumber)
accountFile.write('#')
accountFile.write(catchall)
accountFile.write(':')
accountFile.write(password)
accountFile.write('\n')
signUp()
Expectation would be everything printed to one line but that's not the case.
As a quick fix for your problem, you could merge all writing commands in one line:
with open('accounts.txt', 'a') as accountFile: # using a context manager is highly recommended
# with spaces
accountFile.write('{} {} {} # {} : {} \n'.format(
firstNameChoice,
lastNameChoice,
randomNumber,
catchall,
password
)
)
# without spaces
accountFile.write('{}{}{}#{}:{}\n'.format(
firstNameChoice,
lastNameChoice,
randomNumber,
catchall,
password
)
)
If my understanding is right then you want to write everything in one line.
The variables you are writing containing \n while writing into the file.
So you have to replace it with a ' '. Replace this code into your program like:
accountFile.write(firstNameChoice.replace('\n',' '))
accountFile.write(lastNameChoice.replace('\n',' '))
accountFile.write(str(randomNumber).replace('\n',' '))
accountFile.write('#'.replace('\n',' '))
#accountFile.write(catchall)
accountFile.write(':'.replace('\n',' '))
accountFile.write(str(password).replace('\n',' '))
Now it will print like this WilliamWilliam448#:dsada
By the way I dont know what you mean by catchall
The reason it puts it all on a new line is because the strings of your names contains the "\n" on the end because it has an enter to a new line. There is an easy fix for this.
Where you define your first and last name variables add .rstrip() at the end. Like this:
firstNameChoice = random.choice(lines).rstrip()
lastNameChoice = random.choice(lines).rstrip()
def signUp():
randomNumber = str(random.randint(0,10000))
accountFile = open('accounts.txt', 'a')
accountFile.write(f'{firstNameChoice} {lastNameChoice} {randomNumber} # {catchall}: {password} \n')
So I'm currently trying to write some code that opens and reads a text file. The text file contains a short paragraph. Within the paragraph, there are some words with brackets around them, which could look like: "the boy [past_tense_verb] into the wall." I am trying to write code that looks for the brackets in the text file, and then displays to the user the words in the text file, for the user to then write some input that will replace the bracketed words. This is the code I have so far:
f = open('madlib.txt', 'r')
for line in f:
start = line.find('[')+1
end = line.find(']')+1
word = line[start:end+1]
inputword = input('Enter a ' + word + ': ')
print(line[:start] + inputword + line[end:])
Any help is greatly appreciated - thanks!
import re
with open('madlib.txt', 'r') as f:
data = f.read()
words_to_replace = re.findall(r"\[(\w+)\]", data)
replace_with = []
for idx, i in enumerate(words_to_replace):
print(f"Type here replace \033[1;31m{i}\033[1;m with:", end =" ")
a = input()
replace_with.append(a)
for idx, i in enumerate(replace_with):
data = data.replace(words_to_replace[idx], i)
with open('newmadlib.txt', 'w') as f:
f.write(data)