首页 > 解决方案 > 删除文件中正斜杠后的字符

问题描述

我有一个包含以下内容的 .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("/")]

预期的结果是这样的:

邮政

得到

得到

你能在正确的代码部分帮助我吗?

标签: pythonfilecsv

解决方案


您只需要读取每一行,然后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

推荐阅读