How to delete a tuple from a file in python - python

imp,2,6,7
ads,4,5,6
sfd,2,5,8
I have a text file that looks like this
I want to delete the line that has imp in it.
All the other methods I have seen to delete lines from files only work for single strings

Following this question link, you can try this:
fn = 'Test.txt'
f = open(fn)
output = []
for line in f:
if not "imp" in line:
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
Result:
ads,4,5,6
sfd,2,5,8

Related

Go through files in given directory with python, read each file line by line and remove first and last string in the line and save updated file

So I have some .txt files inside of directory. Each .txt file contains some paths like:
'C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module.c'
'C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module2.c'
'C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module3.c'
I need just some small function that will go through each line of each file inside of a dir and remove there ', so only clear path is left like:
C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module.c
C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module2.c
C:\d\folder\project\folder\Folder1\Folder2\Folder3\Module3.c
My code at the moment is:
for filename in files:
with open(filename, 'r') as file:
content = file.read().split('\n')
for line in content:
if line.startswith('')and line.endswith(''):
remove('')
Please assist!
SOLUTION:
I have managed to find a solution with a bit different approach:
for filename in files:
f = open(filename, 'rt')
filedata = f.read()
filedata = filedata.replace("'","")
f.close()
f = open(filename, 'wt')
f.write(filedata)
f.close()
Thanks!
python has a hirarchy to strings ', ", "" and so on so you can wrap a uptick into quotes for a split. Since we have the first element '' before the tick the second is your path
line.split("'")[1]
Edit: If i understood you correctly you want this
for filename in files:
paths = []
with open(filename, 'r') as file:
content = file.read().split('\n')
for line in content:
paths.append(line.split("'")[1])
file.close()
with open(filename, 'w') as file:
file.writelines(paths)
file.close()
Soo I just did bit different approach and managed to find a solution:
for filename in files:
f = open(filename, 'rt')
filedata = f.read()
filedata = filedata.replace("'","")
f.close()
f = open(filename, 'wt')
f.write(filedata)
f.close()
Thanks guys anyway!

How to delete all characters after a "==" in each line of a file and update the file, using python script?

I have a huge list of python packages that had been installed saved with the version numbers in the file "foo.txt", I want to delete the "==" and whatever after that in each lines, and save the file.
example text in the file:
autopep8==1.5.3
beautifulsoup4==4.8.2
bleach==3.1.4
bumpversion==0.5.3
... etc
Use this line of code if you want to create a new file with updated data, if you want to just read use the data then make changes accordingly.
def read_write_file(input_path, output_path):
with open(input_path, "r") as input_file:
content = input_file.readlines()
with open(output_path, 'w') as output_file:
for line in content:
line = line[:line.find('==')]
output_file.write(line + '\n')
Use the below code.
read that file and store it in list named pkg_list.
output_lst = []
with open("input.txt", "r") as f:
input_data = f.readlines()
output_lst = [name.split("==")[0] for name in input_data]
with open("input.txt", "w") as f:
for pkg in output_lst:
f.write("{}\n".format(pkg))

How to compare all lines in some file with another line?

I am new at Python and need some help.
I have a file with x number of lines. I want to compare each line of that file with another line, and write that line to that file if they are different.
I looked for an answer but didn't find anything that I can use. I tried something myself but it doesn't work.
My code:
filename = ...
my_file = open(filename, 'r+')
for line in my_file:
new_line = ("text")
print line
print new_line
if new_line == line:
print('same')
else:
print('diffrent')
my_file.write('%s' % (new_line))
I only want my application to write the line to the file if it doesn't already exist there.
contents of filename
====================
text
text1
text2
In the case above where new line is "text", the application shouldn't do anything because that line already exist in the file. However, if the new line is "text3" then it should be written to the file as follows:
contents of filename
====================
text
text1
text2
text3
First, let's read the contents of the file so that we can check if the new line is already in there.
existing_lines = [line.rstrip('\n') for line in open(filename, 'r')]
Let's say you have a separate list named new_lines that contains all lines you'd like to check against the file. You can then check to see which ones are new as follows:
new = [line for line in new_lines if line not in existing_lines]
These are the lines that you'd then like to append to your existing file:
with open(filename, 'a') as f:
[f.write(line + '\n') for line in new]
with open('1.txt') as f1, open('2.txt') as f2, open('diff.txt','w') as dst:
while True:
l1 = f1.readline()
l2 = f2.readline()
if not l1 and not l2:
break
if l1 != l2:
dst.write(l1)
I would rather suggest you to create a new file and write the difference to the new file instead of editing the file2.txt
with open("file1.txt", "r") as first_file, open("file2.txt", "r") as second_file:
file1 = first_file.readlines()
file2 = second_file.readlines()
length = min(len(file1), len(file2))
for i in xrange(length):
if file1[i].strip() != file2[i].strip():
#Do something here

Append in each line of a .txt file a specific string using Python

I have a .txt file with has the following format:
/Users/my_user/folder1/myfile.dat
/Users/my_user/folder2/myfile.dat
/Users/my_user/folder3/myfile.dat
.
.
.
so on
I want to append in the end of each line another folder path in order to make it look like this:
/Users/my_user/folder1/myfile.dat,/Users/my_user/folder1/otherfile.dat
/Users/my_user/folder2/myfile.dat,/Users/my_user/folder1/otherfile.dat
/Users/my_user/folder3/myfile.dat,/Users/my_user/folder1/otherfile.dat
.
.
.
so on
Till now I have tried in a loop:
with open("test.txt", "a") as myfile:
myfile.write("append text")
But i only writes at the end of the file.
You could use re.sub function.
To append at the start of each line.
with open("test.txt", "r") as myfile:
fil = myfile.read().rstrip('\n')
with open("test.txt", "w") as f:
f.write(re.sub(r'(?m)^', r'append text', fil))
To append at the end of each line.
with open("test.txt", "r") as myfile:
fil = myfile.read().rstrip('\n')
with open("test.txt", "w") as f:
f.write(re.sub(r'(?m)$', r'append text', fil))
You can try to do something like this:
with open(file_name, 'r') as f:
file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()]
with open(file_name, 'w') as f:
f.writelines(file_lines)

How to Open a file through python

I am very new to programming and the python language.
I know how to open a file in python, but the question is how can I open the file as a parameter of a function?
example:
function(parameter)
Here is how I have written out the code:
def function(file):
with open('file.txt', 'r') as f:
contents = f.readlines()
lines = []
for line in f:
lines.append(line)
print(contents)
You can easily pass the file object.
with open('file.txt', 'r') as f: #open the file
contents = function(f) #put the lines to a variable.
and in your function, return the list of lines
def function(file):
lines = []
for line in f:
lines.append(line)
return lines
Another trick, python file objects actually have a method to read the lines of the file. Like this:
with open('file.txt', 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
With the second method, readlines is like your function. You don't have to call it again.
Update
Here is how you should write your code:
First method:
def function(file):
lines = []
for line in f:
lines.append(line)
return lines
with open('file.txt', 'r') as f: #open the file
contents = function(f) #put the lines to a variable (list).
print(contents)
Second one:
with open('file.txt', 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
print(contents)
Hope this helps!
Python allows to put multiple open() statements in a single with. You comma-separate them. Your code would then be:
def filter(txt, oldfile, newfile):
'''\
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after the name before appending the line to the output file.
'''
with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] + ' - Truly a great person!\n'
outfile.write(line)
# input the name you want to check against
text = input('Please enter the name of a great person: ')
letsgo = filter(text,'Spanish', 'Spanish2')
And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.)
def fun(file):
contents = None
with open(file, 'r') as fp:
contents = fp.readlines()
## if you want to eliminate all blank lines uncomment the next line
#contents = [line for line in ''.join(contents).splitlines() if line]
return contents
print fun('test_file.txt')
or you can even modify this, such a way it takes file object as a function arguement as well
Here's a much simpler way of opening a file without defining your own function in Python 3.4:
var=open("A_blank_text_document_you_created","type_of_file")
var.write("what you want to write")
print (var.read()) #this outputs the file contents
var.close() #closing the file
Here are the types of files:
"r": just to read a file
"w": just to write a file
"r+": a special type which allows both reading and writing of the file
For more information see this cheatsheet.
def main():
file=open("chirag.txt","r")
for n in file:
print (n.strip("t"))
file.close()
if __name__== "__main__":
main()
the other method is
with open("chirag.txt","r") as f:
for n in f:
print(n)

Categories