C Comment Stripper in Python - python

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)

Related

Read/Write Loop Text File with Python

I want to open an existing txt file and search for line of text appearing many times and in different places. Each time search found, insert 2 new rows below it with specified text.
I tried this code but got 'AttributeError' on 'Path.write' line ('str' object has no attribute 'write').
Path = '...\\Test.txt'
searchString = '* Start *'
with open(Path, 'r+') as f:
content = f.readlines()
nextLine = False
for line in content:
if searchString in line:
nextLine = not nextLine
else:
if nextLine:
Path.write('Name\nDirection')
nextLine = not nextLine
else:
pass
I must also allocate to 'Direction' line a number, starting at 0 and increment by 15 until all file is read. So after first instance is found, two lines are inserted into existing txt file like this;
...some text in the existing text file....
* Start *
Name
Direction 0
0 then changes to 15 on next instance (ie Direction 15), then 30 (ie Direction 30) etc until end of file.
EDITED CODE: Simplified coded. Anyone vote me up I'd appreciate
Path = '...\\Test.txt'
direction_number = 0
#Open new file
Newfile = open(Path, 'w')
#read other file
with open(Path, 'r') as f:
content = f.readlines()
#if find special text, write other lines to new file
for line in content:
Newfile.write(line)
if searchString in line:
Newfile.write('Name\nDirection %d' % direction_number)
direction_number += 15
Newfile.close()
Instead of trying to reopen and insert lines into the original file, you should just write a new file. So for each line in the old file, write it to the new file, and write the two additional lines if it contains the text in question.
direction_number = 0
with open("newfile.txt", 'w') as g:
# Loop through every line of text we've already read from
# the first file.
for line in content:
# Write the line to the new file
g.write(line)
# Also, check if the line contains the <searchString> string.
# If it does, write the "Name" and "Direction [whatever]" line.
if searchString in line:
g.write('Name\nDirection %d\n' % direction_number)
direction_number += 15
EDIT: To explain more about this second with open statement: Remember earlier that you used with open(Path, 'r+') as f: to READ your file.
The Path part is where the name of the file is stored, the r+ part means that you're opening it for reading, and the "f" is just a variable that essentially says, "Anything we do on f, we do to the file". Likewise, to start working with a new file, I wrote with open("newfile.txt", 'w') as g:. The "newfile.txt" is the name of the file. The "w" means you're opening up this file for writing to it instead of reading from it (if the file doesn't exist, it will create it; if it exists already, it will completely write over it). Then the "g" is just a variable I picked to refer to this file. So g.write(line) just writes the next line of text from the first file to the next line of text in the second file. I suppose you could use "f" again here, since at this point you've already read all of the lines from the old file. But using a different variable cuts down on any ambiguity of what file you're dealing with, especially if you ever wanted to change this so that you simultaneously have one file still open for reading as you have a second file open for writing.

How to overwrite a file correctly?

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'.

Python: Open a file, search then append, if not exist

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

Editorial iOS : Remove first characters in each line

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)

Not writing to file, even with f.close()

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)

Categories