How to write in a dat file in python - python

I have this content in a dat file I can access easily, it's not at the beggining of the file but in the middle. I insert only the part of the file that I need to modify.
{
....,
",>=,",
",>=,",
.......
}
Instead of a line with ",>=,", I wish I could insert a custom string like for example
"M,<=,5", from python code, as I would have to do this on many files/many times.
I can read the file through this script, but I don't understand how to find the line I want to change in the python code and how to overwrite in it the string of my interest.
prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
with open(prefixed[i], 'r') as file:
lines = file.readlines()
print(lines)

prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
# Read lines
file = open(prefixed[i], 'r')
file_content = file.readlines()
file.close()
# Treatment
for pos, line in enumerate(file_content):
if ",>=," in line:
file_content[pos] = line.replace(",>=,", "myCustomString")
# Write lines
file = open(prefixed[i], 'w')
file.writelines(file_content)
file.close()
To modify only the first element:
prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
# Read lines
file = open(prefixed[i], 'r')
file_content = file.readlines()
file.close()
# Treatment
for pos, line in enumerate(file_content):
if ",>=," in line:
file_content[pos] = line.replace(",>=,", "myCustomString")
# Add break to quit loop after first replacement
break
# Write lines
file = open(prefixed[i], 'w')
file.writelines(file_content)
file.close()

Related

How to read a line while reading a file in Python

Imagine that another filename in the same directory is inside the txt file we're currently in:
For example, let file A be the following:
B.txt
computer
science
How would it be possible to read the other lines and go into B.txt after we're done reading?
If you want to read first line separately, you can do it with readline(). Loop then proceeds to read the file from the second line to the end of file:
import os
def read_files_to_list(wordlist, file):
with open(file, "r") as f:
newfile = f.readline()
newfile = newfile.strip() # removes \n and whitespaces
if not os.path.exists(newfile):
wordlist.append(newfile)
newfile = None
for line in f:
line_clean = line.strip()
wordlist.append(line_clean)
return wordlist, newfile
next_file = "A.txt"
listofwords = []
while next_file is not None:
listofwords, next_file = read_files_to_list(listofwords, next_file)

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 read a file and print it, skipping certain lines in python

I would like to read a file line by line but ignore any that contain a colon (:).
I'm currently opening one file, reading it, and trying to print it before eventually put it into a new file.
def shoppinglist():
infile = open('filename.txt')
contents = infile.readline()
output = open('outputfilename.txt', 'w')
while ":" not in contents:
contents = infile.readline()
else:
contentstr = contents.split()
print(contentstr)
output.write(contents)
infile.close()
output.close()
As it is, one line is repeated over and over and over.
Try:
def shoppinglist():
contents = ""
with open('filename.txt', 'r') as infile:
for line in infile.readlines():
if ":" not in line:
contents += line
with open('outputfilename.txt', 'w') as output_file:
output_file.write(contents)

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