Edited my program - still having same issue
Also, the linked answer that was recommened is useless as it only tells you that you cannot modify a file in place and does not offer any good solution.
I have a file that has line numbers at the start of it. I wrote a python script to eliminate these line numbers. This is my second attempt at it and I am still having the same issues
First I open the file and save it to a variable to reuse later:
#Open for reading and save the file information to text
fin = open('test.txt','r')
text = fin.read()
fin.close
#Make modifications and write to new file
fout = open('test_new.txt','w')
for line in text:
whitespaceloc = line.find(' ')
newline = line[whitespaceloc:]
fout.write(newline)
fout.close()
I have also tried using the 'with' keyword with no luck,
When I open test_new.txt it is empty
What is going on here?
My advice on how to do this would be:
1) Read the file to a buffer:
with open('file.txt','r') as myfile:
lines=myfile.readlines()
2) Now close and overwrite the same file with any changes you want to do just as you did before:
with open('file.txt','w') as myfile:
for line in lines:
whitespaceloc = line.find(' ')
newline = line[whitespaceloc:]
myfile.write("%s" %newline)
Related
I'm trying to create a program using Python that will go through a file containing a git diff (in C code), go through the file, and remove the comments. I tried to read from the file and print a new comment-less version in a different file, but it doesn't seem to be working. I'm also now becoming aware that it will not work for multiline comments.
Here's my code:
write_path = "diff_file" # new file to write in
read_path = "text_diff" # text_diff is the original file with the diff
with open(read_path,'r') as read_file:
text_diff = read_file.read().lower()
for line in read_file:
if line.startswith("/*") and line.endswith("*/"):
with open(write_path, 'a') as write_file:
write_file.write(line + "/n")
For reference, I'm running it under WSL.
I tried this. I changed 'a' to 'w' (write) when opening the output file, and changed its position to avoid opening everytime. I also changed the if condition. That way when there is a comment line it is not printed to the new file.
Also, in endswith I included \n, since a new line is included at the end of the string. And deleted the \n when writing.
write_path = "diff_file" # new file to write in
read_path = "text_diff" # text_diff is the original file with the diff
with open(read_path,'r') as read_file:
text_diff = read_file.readlines()
with open(write_path, 'w') as write_file:
for line in text_diff:
if not (line.startswith("/*") and line.endswith("*/\n")):
write_file.write(line)
I want to load/read a text file and write it to two other text files "entirely". I will write other different data to the following of these two files later.
The problem is that the loaded file is only written to the first file, and no data from that loaded file is written to the second file.
The code I am using:
fin = open("File_Read", 'r')
fout1 = open("File_Write1", 'w')
fout2 = open("File_Write2", 'w')
fout1.write(fin.read())
fout2.write(fin.read()) #Nothing is written here!
fin.close()
fout1.close()
fout2.close()
What is happening and what is the solution?
I prefer using open instead of with open.
Thanks.
Apparently the fin.read() reads all the lines, the next fin.read() will continue from where the previous .read() ended (which is the last line). To solve this, I would simply go for:
text_fin = fin.read()
fout1.write(text_fin)
fout2.write(text_fin)
fin = open("test.txt", 'r')
data = fin.read()
fin.close()
fout1 = open("test2.txt", 'w')
fout1.write(data)
fout1.close()
fout2 = open("test3.txt", 'w')
fout2.write(data)
fout2.close()
N.B. with open is the safest and best way but at least you need to close the file as soon as there are not needed anymore.
You can try iterating through your original file line by line and appending it to both the files. You are running into the problem because file.write() method takes string argument.
fin = open("File_Read",'r')
fout1 = open("File_Write1",'a') #append permissions for line-by-line writing
fout2 = open("File_Write2",'a') #append permissions for line-by-line writing
for lines in fin:
fout1.write(lines)
fout2.write(lines)
fin.close()
fout1.close()
fout2.close()
*** NOTE: Not the most efficient solution.
I would like to know how to overwrite a file in python. When I'm using "w" in the open statement, I still get only one line in my output file.
article = open("article.txt", "w")
article.write(str(new_line))
article.close()
Can you tell me please how can I fix my problem?
If you are in fact looking to overwrite the file line by line, you'll have to do some additional work - since the only modes available are read ,write and append, neither of which actually do a line-by-line overwrite.
See if this is what you're looking for:
# Write some data to the file first.
with open('file.txt', 'w') as f:
for s in ['This\n', `is a\n`, `test\n`]:
f.write(s)
# The file now looks like this:
# file.txt
# >This
# >is a
# >test
# Now overwrite
new_lines = ['Some\n', 'New data\n']
with open('file.txt', 'a') as f:
# Get the previous contents
lines = f.readlines()
# Overwrite
for i in range(len(new_lines)):
f.write(new_lines[i])
if len(lines) > len(new_lines):
for i in range(len(new_lines), len(lines)):
f.write(lines[i])
As you can see, you first need to 'save' the contents of the file in a buffer (lines), and then replace that.
The reason for that is how the file modes work.
"overwrite" is a strange term; especially since you expect to see more than one line from the above code
I am guessing you mean something like "write beyond". The word for that would be "append' and you would want 'a' instead of 'w'.
I am trying to append a string to a file, if the string doesn't exit in the file. However, opening a file with a+ option doesn't allow me to do at once, because opening the file with a+ will put the pointer to the end of the file, meaning that my search will always fail. Is there any good way to do this other than opening the file to read first, close and open again to append?
In code, apparently, below doesn't work.
file = open("fileName", "a+")
I need to do following to achieve it.
file = open("fileName", "r")
... check if a string exist in the file
file.close()
... if the string doesn't exist in the file
file = open("fileName", "a")
file.write("a string")
file.close()
To leave the input file unchanged if needle is on any line or to append the needle at the end of the file if it is missing:
with open("filename", "r+") as file:
for line in file:
if needle in line:
break
else: # not found, we are at the eof
file.write(needle) # append missing data
I've tested it and it works on both Python 2 (stdio-based I/O) and Python 3 (POSIX read/write-based I/O).
The code uses obscure else after a loop Python syntax. See Why does python use 'else' after for and while loops?
You can set the current position of the file object using file.seek(). To jump to the beginning of a file, use
f.seek(0, os.SEEK_SET)
To jump to a file's end, use
f.seek(0, os.SEEK_END)
In your case, to check if a file contains something, and then maybe append append to the file, I'd do something like this:
import os
with open("file.txt", "r+") as f:
line_found = any("foo" in line for line in f)
if not line_found:
f.seek(0, os.SEEK_END)
f.write("yay, a new line!\n")
There is a minor bug in the previous answers: often, the last line in a text file is missing an ending newline. If you do not take that that into account and blindly append some text, your text will be appended to the last line.
For safety:
needle = "Add this line if missing"
with open("filename", "r+") as file:
ends_with_newline = True
for line in file:
ends_with_newline = line.endswith("\n")
if line.rstrip("\n\r") == needle:
break
else: # not found, we are at the eof
if not ends_with_newline:
file.write("\n")
file.write(needle + "\n") # append missing data
I'm trying to create an Editorial workflow to remove the six first characters of each line in a file.
For now, I've builded a new worklfow composed by three steps :
Get selected text
Custom Python script
Replace selected text
My Python script is :
#coding: utf-8
import workflow
action_in = workflow.get_input()
text = open("temp.txt", "w+")
text.write(action_in)
lines = text.readlines()
for line in lines:
text.write(line[6:])
action_out = text.read()
workflow.set_output(action_out)
Actually, when I try to use this workflow on a line, it just erases it.
How should I do?
Thank you in advance.
I suspect the issue is that you need to close “temp.txt” and then re-open it. This works for me:
import workflow
action_in = workflow.get_input()
text = open("temp.txt", "w+")
text.write(action_in)
text.close()
text = open("temp.txt", "r")
lines = text.readlines()
text.close()
text = open("temp.txt", "w+")
for line in lines:
text.write(line[6:])
text.close()
text = open("temp.txt", "r")
action_out = text.read()
workflow.set_output(action_out)
The “w+” in your initial “open” statement erases the file and opens it for read/write; however, the file pointer will follow the write. The safest method is to close the file when done, and re-open it to reset the file pointer and get the data you want.
Since you’re using w+, you might also be able to use .seek() to reposition the file pointer, depending on caching, however, if your outline is all you need, there’s no need to open a temporary file to perform this action.
import workflow
action_in = workflow.get_input()
lines = []
for line in action_in.split("\n"):
lines.append(line[6:])
action_out = "\n".join(lines)
workflow.set_output(action_out)