python - 删除文件中正斜杠后的字符
问题描述
我有一个包含以下内容的 .csv 文件:
头/HTTP/1.1
发布 /app/something1/ HTTP/1.1
获取 /app/something2/ HTTP/1.1
获取 /app/something3/ HTTP/1.1
并且在第一个 fw 斜杠之后找不到删除所有内容的方法。
我尝试了一些正则表达式,但没有这样的知识,它看起来比使用 python 更困难。
这是我尝试过的基本代码:
with open('log1.csv') as f:
for line in f:
f[:f.index("/")]
预期的结果是这样的:
头
邮政
得到
得到
你能在正确的代码部分帮助我吗?
解决方案
您只需要读取每一行,然后split()
对'\'
第一项进行索引:
# Open the file in read more
# mode='r' by default if you don't specify
with open('log1.csv') as f:
# Read each line from the iterator
for line in f:
# Strip newlines
line = line.strip()
# Only process non-empty lines
if line:
# Split the line and take the first item
print(line.split('/')[0])
输出:
HEAD
POST
GET
GET
推荐阅读
- java - 拆分方法中的多个正则表达式使用
- mysql - 如何格式化这种日期?
- python - 快速对象概述算法?(计算机视觉,python)
- python - 为什么我在 .rename 上收到“ftplib.error_perm: 550 Access denied”?
- c++ - 将可变参数函数参数转发到 std::function 对象
- reactjs - 渲染新组件后我无法使用 onCkick 事件
- c++ - C++ std::vector - 如何修改迭代器指定的元素?
- phpunit - C:\phpunittest>./vendor/bin/phpunit 命令不起作用
- java - JUnit执行测试的Spring Boot问题
- rust - 线程 'main' 在 'index out of bounds: the len is 2 but index is 2' 崩溃时惊慌失措