简体   繁体   中英

python: replace every 18th character of every nth line in a text file

Because of the way the dataset I have is formatted, each hourly timestamp is written as 18 0 instead of 1800 (for example), and the extra space instead of a zero is messing up the way that Excel is converting the dataset from a TAB file to a CSV. There are > 600,000 lines, and this happens every 4th line.

see snapshot of dataset

I'm reading the text file in, reading each line, and then trying to replace the 18th character of every 4th line (the wretched space) with a 0

I think I am incorrectly understanding how to make each line a string, and also not sure how to correct the line and then re-save it into the file that will be ready to convert to a CSV

Python strings are immutable, and so they do not support item or slice assigment. You'll have to build a new string using ie someString[:18] + 'a' + someString[19:] or some other suitable approach, then storing it in the file again..

string = "18 0"
string = string.replace(" ","0")

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