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)
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 want to do a lot of boring C# code replacements automatically through a python script. I read all lines of the file, transform them, truncate the whole file, write new strings and close it.
f = open(file, 'r+')
text = f.readlines()
# some changes
f.truncate(0)
for line in text:
f.write(line)
f.close()
All my changes are written. But some strange characters in the beginning of the file appear. I don't know how to avoid them. Even if I open with encoding='utf-8-sig' it doesn't help.
I tried truncate whole file besides the 1st line like this:
import sys
f.truncate(sys.getsizeof(text[0]))
for index in range(1, len(text), 1):
f.write(text[index])
But in this case more than 1st line is writing instead of only first line.
EDIT
I tried this:
f.truncate(len(text[0]))
for index in range(1, len(text), 1):
f.write(text[index])
And the first line has written correct but next one with the same issue. So I think this characters from the end of the file and I try to write after them.
f=open(file, 'r+')
text = f.readlines() # After reading all the lines, the pointer is at the end of the file.
# some changes
f.seek(0) # To bring the pointer back to the starting of the file.
f.truncate() # Don't pass any value in truncate() as it means number of bytes to be truncated by default size of file.
for line in text:
f.write(line)
f.close()
Check out this Link for more details.
Similar to posting: Replace string in a specific line using python, however results were not forethcomming in my slightly different instance.
I working with python 3 on windows 7. I am attempting to batch edit some files in a directory. They are basically text files with .LIC tag. I'm not sure if that is relevant to my issue here. I am able to read the file into python without issue.
My aim is to replace a specific string on a specific line in this file.
import os
import re
groupname = 'Oldtext'
aliasname = 'Newtext'
with open('filename') as f:
data = f.readlines()
data[1] = re.sub(groupname,aliasname, data[1])
f.writelines(data[1])
print(data[1])
print('done')
When running the above code I get an UnsupportedOperation: not writable. I am having some issue writing the changes back to the file. Based on suggestion of other posts, I edited added the w option to the open('filename', "w") function. This causes all text in the file to be deleted.
Based on suggestion, the r+ option was tried. This leads to successful editing of the file, however, instead of editing the correct line, the edited line is appended to the end of the file, leaving the original intact.
Writing a changed line into the middle of a text file is not going to work unless it's exactly the same length as the original - which is the case in your example, but you've got some obvious placeholder text there so I have no idea if the same is true of your actual application code. Here's an approach that doesn't make any such assumption:
with open('filename', 'r') as f:
data = f.readlines()
data[1] = re.sub(groupname,aliasname, data[1])
with open('filename', 'w') as f:
f.writelines(data)
EDIT: If you really wanted to write only the single line back into the file, you'd need to use f.tell() BEFORE reading the line, to remember its position within the file, and then f.seek() to go back to that position before writing.
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)