Recently, the data file format provided in the project that I took over is simply not going to be seen. The use of pandas can not be opened, has been IO error. A close look, found that many rows of data in the file are "end, but other lines are missing, and therefore the demand is very obvious:" To determine whether the end of each line has ", no, Plus, that's good.
A flashback is a good way, after all, a lot of people need just a quick solution, not a why. The solution is as follows:
b = Open (' B_file.txt ', W) with
open (' A_file.txt ', ' r ') as lines: for line in
lines: line
= Line.strip ()
if Not Line.endswith (R ' ""): line
+ R ' "' line
+ = \ n '
b.write (line)
b.close ()
a.close ()
The key to the whole process is
Before I was lazy, direct use omitted the above line, the result in the judgment condition fell, the program that each line is not "end:"
If not Line.endswith (R ' "')
Bite the bullet and try to rewrite:
For line in open (data_path+ ' heheda.txt ', ' R '):
if not line[-2] = = R ' ":
print line
= line[:-1] + R '" ' + line[-1:]
Print Line
At this point the condition is judged if not line[-2] == r'"'
so that the correct result can be obtained except the last line. As a well-known reason, in Windows systems, a file's carriage return is "\ r \ n", and therefore, when no strip () is processed for a carriage return, you need to manually move the end of each line forward by moving one byte to the end of each line. And for the last line of the file, generally not a carriage return as the end, after all, do not change the line. Thus Line[-2] is positioned to the middle of the last Chinese character, \xx\xx, hard written \xx "\xx, making the last Word display error.
The above is a small series to introduce the Python contains Chinese characters in the file read and write the end of each line with a specific character, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!