简体   繁体   English

删除文件中正斜杠后的字符

[英]Remove characters after forward slash in file

I have a.csv file with this content:我有一个包含以下内容的.csv 文件:

HEAD / HTTP/1.1头/HTTP/1.1

POST /app/something1/ HTTP/1.1发布 /app/something1/ HTTP/1.1

GET /app/something2/ HTTP/1.1获取 /app/something2/ HTTP/1.1

GET /app/something3/ HTTP/1.1获取 /app/something3/ HTTP/1.1

and can't find a way to remove everything after the first fw slash.并且在第一个 fw 斜杠之后找不到删除所有内容的方法。

I've tried some regex but without such a knowledge it looks more difficult than going with python.我尝试了一些正则表达式,但没有这样的知识,它看起来比使用 python 更困难。

This is basic code that I've tried:这是我尝试过的基本代码:

with open('log1.csv') as f:
    for line in f:
        f[:f.index("/")]

The expected result is this:预期的结果是这样的:

Head

POST邮政

GET得到

GET得到

Can you please assist me on the right code portion?你能在正确的代码部分帮助我吗?

You just need to read each line in, and split() on '\' and index the first item:您只需要读取每一行,然后split() on '\'并索引第一项:

# 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])

Output: Output:

HEAD 
POST 
GET
GET

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

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