简体   繁体   中英

Add character at the beginning of line with specific string in line - Python

I have a file with few thousand lines like this:

0.5  AA
2.7 AA
45.2 AA
567.1 CC
667.5 AA 
4456 AA
1005.2 CC

I want add comment signs "//" at the beginning of each line contains string "CC".

I have code like this:

import fileinput

file_name = input("file path: ")

for line in fileinput.FileInput(file_name, inplace=1):
    if 'CC' in line:
        line = line.rstrip()
        line = line.replace(line,'// '+line)
    print (line)

Everything works fine but the file looks like that after execute the code:

0.5  AA

2.7 AA
    
45.2 AA
    
// 567.1 CC
667.5 AA
    
4456 AA
    
// 1005.2 CC

Why after execute the code i have the new line spaces after line without changes? How I can remove this? Second question is: How i can save this file as a new file?

Summarizing: I need to write code which in a txt file will add "//" to the beginning of each line containing "CC" and save it as a new file.

This solution works well, what you think about it ?

filepath = input("original file :")
filepath2 = input("result file : ")

with open(filepath, "r") as f, open(filepath2, "w") as f2:
    for line in f:
        f2.write(line if not 'CC' in line else "//" + line)

It seems like a character issue in your input file. Maybe .strip() instead of .rstrip() will work better. .rstrip() only removes whitespaces at the right of the string while .strip() removes them left and right. Something like this should work:

inputFile = open('data.txt', 'r')
outputFile = open('outputFile.txt', 'w')

for line in inputFile:

    outputLine = line.strip() + '\n'
    if 'CC' in line:
        outputLine = '//' +  outputLine
    outputFile.write(outputLine)
 
inputFile.close()
outputFile.close()

The extra new lines is due to the '\\n' characters present already in lines of the file, you can prevent that by changing to

print(line, end='')

I dont know why you prefer file input module for reading files, becuase I find the default method open to be quite satisfactory as you can read and write textfiles, binaryfiles, etc... As for your question:

with open(file_name, 'w') as file:
    file.write(data)

here is a solution :

p="name_of_original_file.txt"
file=open(p,"r")
s=file.read()
file.close() 

new_s=""
for line in s.splitlines():
    if 'CC' not in line:
        new_s+=line+"\n"
    if 'CC' in line:
        new_s+='// '+line+"\n"
    print (line)

p="name_of_new_file.txt"
file=open(p,"w")
file.write(new_s)
file.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM