Appending in Python 3 from a list - python-3.x

def add():
aList = input("Enter file name with file extension too: ")
file = open(aList, "a")
txt = input("Enter the text you would like to add on to the txt file: ")
aList.append (txt);
print ("Updated List : ", aList)
I need this to append on to an external file like this:
NIGHT
SMOKE
GHOST
TOOTH
ABOUT
CAMEL
BROWN
FUNNY
CHAIR
PRICE
This list is called "List.txt"
I input this as the first variable and for the second variable I input "Hello" but I'm not really sure why it's giving me an error.
I just need it to add on to this list...

If you open a file in append-Mode, you can simply use write to add the text at the end of the file. The additional '\n' inserts a line break so the new input will be on an extra line.
aList = input("Enter the file name with the file extension too: ")
file = open(aList, "a")
txt = input("Enter the text you would like to add on to the txt file: ")
file.write(txt + '\n');
file.close()
print ("Updated List : ", aList)
Also please make sure that you close the file at the end of use. Or even better use the with statement which will close the file at the and of the block.
aList = input("Enter the file name with the file extension too: ")
with open(aList, "a") as file:
txt = input("Enter the text you would like to add on to the txt file: ")
file.write(txt + '\n')
print("Updated List : ", aList)

Related

using python to parse through files for data

I have two files one template file and one file which has the values for the template file. I am trying to take the template file and then pass values to the variables from another file and combine the two into a third file. I am able to copy one file to another using the following snippet of code
`
print("Enter the Name of Source File: ")
sFile = input()
print("Enter the Name of Target File: ")
tFile = input()
fileHandle = open(sFile, "r")
texts = fileHandle.readlines()
fileHandle.close()
fileHandle = open(tFile, "w")
for s in texts:
fileHandle.write(s)
fileHandle.close()
print("\nFile Copied Successfully!")
`
however I am not sure how to do it for two or more files and then to make them into one file. Any help/guidance is appreciated
This is certainly not the most elegant solution but I think it should work for you.
# You could add as many files to this list as you want.
list_of_files = []
count = 1
while True:
print(f"Enter the Name of Source File{count} (Enter blank when done adding files): ")
sFile = input()
# If the input is not empty then add the filename to list_of_files.
if sFile:
list_of_files.append(sFile)
count += 1
else:
break
print("Enter the Name of Target File: ")
tFile = input()
# With open will open the file and then close if when done.
with open(tFile, 'a+') as target:
# This will loop over all the files in your list.
for file in list_of_files:
tmp = open(file, 'r')
target.write('\n' + tmp.read())
tmp.close()

What's a better way to delete a row of text from a text file?

I want to delete a row of text from a text file. This is my code:
with open("contactbook.txt","r") as file:
for num, line in enumerate(file, 1):
if args.name in line:
filedata = file.read()
filedata = filedata.replace(line, " ")
with open('contactbook.txt', 'w') as file:
file.write(filedata)
The texts are arranged like this:
Name:Hello Phone number: 9 Address: 9 E-mail: 9
Name:Hi Phone number: 8 Address: 8 E-mail: 8
NOTE: The actual file contains a lot of rows, the one above just shows how it looks like.
So for example, if I want to delete the row containing "Hi", I only want the following to remain.
Name:Hello Phone number: 9 Address: 9 E-mail: 9
NOTE: The user input is only "Hi" but it will delete the entire row where it is found.
My code works sometimes but there are times it ends up deleting everything (the entire content of the text file), what am I doing wrong and what's a better way to do this?
Try this it simple and easy
a_file = open("sample.txt", "r")
lines = a_file.readlines()
a_file.close()
a= int( input("enter the line which you want to delete:"))
del lines[a]
new_file = open("sample.txt", "w+")
for line in lines:
new_file.write(line)
new_file.close()
You can use readlines() which will read the lines into a list.
Once the list is created you can apply list comprehension.
See below:
my_file = open("contactbook.txt", "r")
content_list = my_file.readlines()
print(content_list)
simple_new = [i for i in content_list if 'Hi' not in i]
print(simple_new)
with open("outfile.txt", "w") as outfile:
outfile.write("".join(simple_new))
You can use regex if you want to have more options like Ignore Case, etc.
regex_pattern = '^((?!Hi).)*$'
moreoptions_new = [i for i in content_list if re.search(regex_pattern, i, re.IGNORECASE)]
print(moreoptions_new)
with open("outfile2.txt", "w") as outfile:
outfile.write("".join(moreoptions_new))

Find items in a text file that is a incantinated string of capitalized words that begin with a certain capital letter in python

I am trying to pull a string of input names that get saved to a text file. I need to pull them by capital letter which is input. I.E. the saved text file contains names DanielDanClark, and I need to pull the names that begin with D. I am stuck at this part
for i in range(num):
print("Name",i+1," >> Enter the name:")
n=input("")
names+=n
file=open("names.txt","w")
file.write(names)
lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
quit()
else:
letter=input("Enter the first letter of the names you want to look up in uppercase:")
file=open("names.txt","r")
fileNames=[]
file.list()
for letter in file:
fileNames.index(letter)
fileNames.close()
I know that the last 4 lines are probably way wrong. It is what I tried in my last failed attempt
Lets break down your code block by block
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n=input("")
names+=n
I took the liberty of giving num a value of 5, and names a value of "", just so the code will run. This block has no problems. And will create a string called names with all the input taken. You might consider putting a delimiter in, which makes it more easier to read back your data. A suggestion would be to use \n which is a line break, so when you get to writing the file, you actually have one name on each line, example:
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n = input()
names += n + "\n"
Now you are going to write the file:
file=open("names.txt","w")
file.write(names)
In this block you forget to close the file, and a better way is to fully specify the pathname of the file, example:
file = open(r"c:\somedir\somesubdir\names.txt","w")
file.write(names)
file.close()
or even better using with:
with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
openfile.write(names)
The following block you are asking if the user want to lookup a name, and then exit:
lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
quit()
First thing is that you are using quit() which should not be used in production code, see answers here you really should use sys.exit() which means you need to import the sys module. You then proceed to get the numeric value of the answer being either N or n and you check this in a if statement. You do not have to do ord() you can use a string comparisson directly in your if statement. Example:
lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
sys.exit()
Then you proceed to lookup the requested data, in the else: block of previous if statement:
else:
letter=input("Enter the first letter of the names you want to look up in uppercase:")
file=open("names.txt","r")
fileNames=[]
file.list()
for letter in file:
fileNames.index(letter)
fileNames.close()
This is not really working properly either, so this is where the delimiter \n is coming in handy. When a text file is opened, you can use a for line in file block to enumerate through the file line by line, and with \n delimiter added in your first block, each line is a name. You also go wrong in the for letter in file block, it does not do what you think it should be doing. It actually returns each letter in the file, regardless of whay you type in the input earlier. Here is a working example:
letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
for line in openfile: ## loop thru the file line by line
line = line.strip('\n') ## get rid of the delimiter
if line[0].lower() == letter.lower(): ## compare the first (zero) character of the line
result.append(line) ## append to result
print(result) ## do something with the result
Putting it all together:
import sys
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n = input("")
names += n + "\n"
with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
openfile.write(names)
lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
sys.exit()
letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
for line in openfile:
line = line.strip('\n')
if line[0].lower() == letter.lower():
result.append(line)
print(result)
One caveat I like to point out, when you create the file, you open the file in w mode, which will create a new file every time, therefore overwriting the a previous file. If you like to append to a file, you need to open it in a mode, which will append to an existing file, or create a new file when the file does not exist.

this codes output needs to be sent to a seperate text file, why does no work

i have got this piece of code to find the positions of the first occuring of that word and replace them into the actual program.
i have tried this
sentence = "ask not what you can do for your country ask what your country can do for you"
listsentence = sentence.split(" ")
d = {}
i = 0
values = []
for i, word in enumerate(sentence.split(" ")):
if not word in d:
d[word] = (i + 1)
values += [d[word]]
print(values)
example = open('example.txt', 'wt')
example.write(str(values))
example.close()
how do i write this output to a seperate text file such as notepad.
Actually your code works- example.txt is created each time you run this program. You can check that in your directory this file exists.
If you want to open it right after closing it in your script add:
import os
os.system("notepad example.txt")

Something's wrong with my Python code (complete beginner)

So I am completely new to Python and can't figure out what's wrong with my code.
I need to write a program that asks for the name of the existing text file and then of the other one, that doesn't necessarily need to exist. The task of the program is to take content of the first file, convert it to upper-case letters and paste to the second file. Then it should return the number of symbols used in the file(s).
The code is:
file1 = input("The name of the first text file: ")
file2 = input("The name of the second file: ")
f = open(file1)
file1content = f.read()
f.close
f2 = open(file2, "w")
file2content = f2.write(file1content.upper())
f2.close
print("There is ", len(str(file2content)), "symbols in the second file.")
I created two text files to check whether Python performs the operations correctly. Turns out the length of the file(s) is incorrect as there were 18 symbols in my file(s) and Python showed there were 2.
Could you please help me with this one?
Issues I see with your code:
close is a method, so you need to use the () operator otherwise f.close does not do what your think.
It is usually preferred in any case to use the with form of opening a file -- then it is close automatically at the end.
the write method does not return anything, so file2content = f2.write(file1content.upper()) is None
There is no reason the read the entire file contents in; just loop over each line if it is a text file.
(Not tested) but I would write your program like this:
file1 = input("The name of the first text file: ")
file2 = input("The name of the second file: ")
chars=0
with open(file1) as f, open(file2, 'w') as f2:
for line in f:
f2.write(line.upper())
chars+=len(line)
print("There are ", chars, "symbols in the second file.")
input() does not do what you expect, use raw_input() instead.

Resources