How can I remove a string from a txt file? - python

I am trying to create a contact info txt file with python
what_you_want = input("Do you want to add or remove (if add write add), (if remove write remove): ")
if what_you_want == "remove":
what_you_want_remove = input("What contact number you want to remove: ")
with open("All Contact.txt", "r") as f:
contact_info = f.readlines()
if what_you_want_remove in contact_info:
with open("All Contact.txt", "a") as f:
if what_you_want_remove in contact_info:
new_contact_info = contact_info.replace(what_you_want_remove, "")
f.write(new_contact_info)
I couldn't find a way to directly remove something from a txt file so I want to put it into a list and then write it back to txt file but when I try to use remove command it doesn't work.
I want to ask if there is a way to remove something from a text file directly.

You can read the file into a string or list, remove the substring, and write back to the file. For instance,
with open("file.txt", "w") as f:
string = f.readlines()
string = string.replace(substring, "")
f.write(string)
If substring does not exist in file.txt, the replace function will not perform any action. If you want the replacement to be case-insensitive, you could try lowering the entire buffer as well as the subtring via string = string.lower() and substring = substring.lower().

Use del to delete that entry.
Then overwrite the original file, making it one line shorter.
if what_you_want_remove in contact_info:
i = contact_info.index(what_you_want_remove)
del contact_info[i]
with open("All Contact.txt", "w") as fout:
fout.write("\n".join(contact_info)
fout.write("\n")

Related

read keyword in txt file, and print add text + keyword

I got many keywords in txt file to python using f = open().
And I want to add text before each keywords.
example,
(http://www.google.com/) + (abcdefg)
add text keywords imported
It have tried it, I can't result I want.
f = open("C:/abc/abc.txt", 'r')
data = f.read()
print("http://www.google.com/" + data)
f.close()
I tried it using "for".
But, I can't it.
Please let me know the solution.
many thanks.
Your original code has some flaws:
you only read the first line of the file, with data = f.read(). If you want to read all the lines from the file, use a for;
data is a str-type variable, which may have more than one word. Thus, you must split this line into words, using data.split()
To solve your problem, you need to read each line from the file, split the line into the words it has, then loop through the list with the words, add the desired text then the word itself.
The correct program is this:
f = open("C:/abc/abc.txt", 'r')
for data in f:
words = data.split()
for i in words:
print("http://www.google.com/" + i)
f.close()
with open('text.txt','r') as f:
for line in f:
print("http://www.google.com/" + line)

How to open a file in python, read the comments ("#"), find a word after the comments and select the word after it?

I have a function that loops through a file that Looks like this:
"#" XDI/1.0 XDAC/1.4 Athena/0.9.25
"#" Column.4: pre_edge
Content
That is to say that after the "#" there is a comment. My function aims to read each line and if it starts with a specific word, select what is after the ":"
For example if I had These two lines. I would like to read through them and if the line starts with "#" and contains the word "Column.4" the word "pre_edge" should be stored.
An example of my current approach follows:
with open(file, "r") as f:
for line in f:
if line.startswith ('#'):
word = line.split(" Column.4:")[1]
else:
print("n")
I think my Trouble is specifically after finding a line that starts with "#" how can I parse/search through it? and save its Content if it contains the desidered word.
In case that # comment contain str Column.4: as stated above, you could parse it this way.
with open(filepath) as f:
for line in f:
if line.startswith('#'):
# Here you proceed comment lines
if 'Column.4' in line:
first, remainder = line.split('Column.4: ')
# Remainder contains everything after '# Column.4: '
# So if you want to get first word ->
word = remainder.split()[0]
else:
# Here you can proceed lines that are not comments
pass
Note
Also it is a good practice to use for line in f: statement instead of f.readlines() (as mentioned in other answers), because this way you don't load all lines into memory, but proceed them one by one.
You should start by reading the file into a list and then work through that instead:
file = 'test.txt' #<- call file whatever you want
with open(file, "r") as f:
txt = f.readlines()
for line in txt:
if line.startswith ('"#"'):
word = line.split(" Column.4: ")
try:
print(word[1])
except IndexError:
print(word)
else:
print("n")
Output:
>>> ['"#" XDI/1.0 XDAC/1.4 Athena/0.9.25\n']
>>> pre_edge
Used a try and except catch because the first line also starts with "#" and we can't split that with your current logic.
Also, as a side note, in the question you have the file with lines starting as "#" with the quotation marks so the startswith() function was altered as such.
with open('stuff.txt', 'r+') as f:
data = f.readlines()
for line in data:
words = line.split()
if words and ('#' in words[0]) and ("Column.4:" in words):
print(words[-1])
# pre_edge

List and String formatting difficulties: importing a txt file, adding strings and writing it to a new file

I'm having trouble with list and string formatting, and writing the changes to a new file. What I'm looking for is:
STRINGS BEFORE
imported txt file contents (a list of string values)
STRINGS AFTER
Where both the preceding and following STRINGS are already defined, and everything is written to a new file!
My end goal, is so that when i import a txt file (containing a list) and run the code, it then is printed to a new file with pre-defined strings added before and after the imported txt file's list.
My code right now is as follows:
text_file = open(r"text_file path", "r")
lines = text_file.read().split(',')
lines.insert(0, "String Values Before")
lines.insert("String Values After")
text_file.close()
lines.write("new_file.txt", "w+")
The problem now is that I am inserting to the list, whereas I want the strings to be separate to the list!
I've been able to produce what I want the written file to look like in the console with this code here:
FIRMNAME = "apple"
FILETYPE = "apple"
REPLYFILENAME = "apple"
SECMASTER = "apple"
PROGRAMNAME = "apple"
text_file = open(r"textfile path", "r+")
lines = text_file.readlines().split('\n')
print(("START-OF-FILE \nFIRMNAME= ") + FIRMNAME)
print(("FILETYPE= ") + FILETYPE)
print(("REPLYFILENAME= ") + REPLYFILENAME)
print(("SECMASTER= ") + SECMASTER)
print(("PROGRAMNAME= ") + PROGRAMNAME)
print("START-OF-FIELDS")
print("END-OF-FIELDS")
print("START-OF-DATA")
pprint.pprint(lines)
print("END-OF-DATA")
print("END-OF-FILE")
I just can't figure out how to write this to a new file! Help!
You could solve it this way:
newFile = 'your_new_file.txt'
oldFile = 'your_old_file.txt'
# Open the new text file
with open(newFile, 'w') as new_file:
# Open the old text file
with open(oldFile, 'r') as old_file:
# Write the line before the old content
new_file.write('Line before old content\n')
# Write old content
for line in old_file.readlines():
new_file.write(line)
# Write line after old content
new_file.write('Line after old content')
Your variable lines is of type list, which does not have a method write.
Furthermore insert requires a position, that your second call is lacking.
You'll need to read the file, concat it with the prefix and suffix values accordingly and then write it to the appropriate output file:
with open("text_file_path", "r") as input_file:
text = input_file.read()
text = '\n'.join(("String Values Before", text, "String Values After"))
with open("new_file.txt", "w+") as output_file:
output_file.write(text)
Use pformat.
pprint
before_values = ["a", "b", "c"]
data = ["1", "2", "3"]
after_values = ["d", "e", "f"]
with open("outfile.txt", "w) as outfile:
outfile.write("\n".join(before_values)) # Write before values
outfile.write(pprint.pformat(data)) # Write data list
outfile.write("\n".join(after_values)) # Write after values
You have an error you originally call the insert method as you must provide an index; however, you can just append, join the resulting list, and write to the file:
text_file = open(r"text_file path", "r")
lines = text_file.read().split(',')
lines.insert(0, "String Values Before")
lines.append("String Values After")
text_file.close()
new_file = open('text_file_path.txt', 'w')
new_file.write(','.join(lines)+'\n')
new_file.close()

Removing data from a list from a raw_input variable

So I'm fairly new to Python. After going through a few different tutorials and such I've decided to try and make a simple program, one of the things in it I need it to remove a line in a txt file. Here's the code I currently have:
name = raw_input("What name would you like to remove: ")
templist = open("oplist.txt").readlines()
templist_index = templist.index(name)
templist.remove(templist_index)
target = open("oplist.txt", "w")
target.write(templist)
target.close
However when templist is made it stores the data like "example1\n" which if the user only typed example it wouldn't work. Is there any simpler ways to this or fix? Thanks for the assistance.
use rstrip to remove the newlines chars and use with to open your files:
with open("oplist.txt") as f: # with opens and closes the file automtically
templist = [x.rstrip() for x in f] # strip new line char from every word
You could also concat a newline char to name:
templist_index = templist.index(name+"\n") # "foo" -> "foo\n"
The full code:
with open("oplist.txt") as f:
temp_list = [x.rstrip() for x in f]
name = raw_input("What name would you like to remove: ")
temp_list.remove(name) # just pass name no need for intermediate variable
with open("oplist.txt", "w") as target: # reopen with w to overwrite
for line in temp_list: # iterate over updated list
target.write("{}\n".format(line)) # we need to add back in the new line
# chars we stripped or all words will be on one line

Opening a file in Python

Question:
How can I open a file in python that contains one integer value per line. Make python read the file, store data in a list and then print the list?
I have to ask the user for a file name and then do everything above. The file entered by the user will be used as 'alist' in the function below.
Thanks
def selectionSort(alist):
for index in range(0, len(alist)):
ismall = index
for i in range(index,len(alist)):
if alist[ismall] > alist[i]:
ismall = i
alist[index], alist[ismall] = alist[ismall], alist[index]
return alist
I think this is exactly what you need:
file = open('filename.txt', 'r')
lines = [int(line.strip()) for line in file.readlines()]
print(lines)
I didn't use a with statement here, as I was not sure whether or not you intended to use the file further in your code.
EDIT: You can just assign an input to a variable...
filename = input('Enter file path: ')
And then the above stuff, except open the file using that variable as a parameter...
file = open(filename, 'r')
Finally, submit the list lines to your function, selectionSort.
selectionSort(lines)
Note: This will only work if the file already exists, but I am sure that is what you meant as there would be no point in creating a new one as it would be empty. Also, if the file specified is not in the current working directory you would need to specify the full path- not just the filename.
Easiest way to open a file in Python and store its contents in a string:
with open('file.txt') as f:
contents = f.read()
for your problem:
with open('file.txt') as f:
values = [int(line) for line in f.readlines()]
print values
Edit: As noted in one of the other answers, the variable f only exists within the indented with-block. This construction automatically handles file closing in some error cases, which you would have to do with a finally-construct otherwise.
You can assign the list of integers to a string or a list
file = open('file.txt', mode = 'r')
values = file.read()
values will have a string which can be printed directly
file = open('file.txt', mode = 'r')
values = file.readlines()
values will have a list for each integer but can't be printed directly
f.readlines() read all the lines in your file, but what if your file contains a lot of lines?
You can try this instead:
new_list = [] ## start a list variable
with open('filename.txt', 'r') as f:
for line in f:
## remove '\n' from the end of the line
line = line.strip()
## store each line as an integer in the list variable
new_list.append(int(line))
print new_list

Categories