简体   繁体   English

python:替换文本文件中每第n行的第18个字符

[英]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.由于我拥有的数据集的格式设置方式,每个小时时间戳都写为 18 0 而不是 1800(例如),额外的空间而不是零会扰乱 Excel 从 TAB 文件转换数据集的方式到 CSV。 There are > 600,000 lines, and this happens every 4th line.有 > 600,000 行,每 4 行发生一次。

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我正在读取文本文件,读取每一行,然后尝试用 0 替换每 4 行的第 18 个字符(可怜的空格)

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我想我错误地理解了如何使每一行成为一个字符串,也不确定如何更正该行然后将其重新保存到准备好转换为 CSV 的文件中

Python strings are immutable, and so they do not support item or slice assigment. Python 字符串是不可变的,因此它们不支持项目或切片分配。 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..您必须使用 ie someString[:18] + 'a' + someString[19:]或其他一些合适的方法构建一个新字符串,然后再次将其存储在文件中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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