简体   繁体   中英

Reading a specific text in a file and assigning to a variable in python

I'm trying to read/copy a specific text from a file and assigning it to a variable. File(token.txt) contents are:

  • Other file content *
  • Other file content *
  • Other file content *
  • Other file content *
  • Other file content * Mid-access token: eyJ4NXQjUzI1NiI6IkNiNTFhalJ2THBOTF8ya20zZVA2WUxkbWYydldxUzJhdjh3VGdzVngxV0UiLCJ4NXQiOiJFV2pWcWc3MFoxQTNUcWNtUzhKZTg1blJ1cDgiLCJhbGciOiJSUzI1NiJ9..T_aCXYzT4pThuKic2VEDbSKSc9Yl0upmjun62vPxdEBOYhCiMCbNA_jdFxd_ZVcegZICnQyl8KrD52MCpCjy5G_yMwEjTppnojcWv7FFIYMgpNu664jB4VPeGoiGJU7KH0EtpN6akKT5eSnlRunlqZd4FWSclDckaKhuPuKo8PPf2bzShGb4aH7obYik_RRbAiOf4z1vdM7JKYKo0Co6K1ZNkdZ3_K6hSOtHoNhHc6B6uay_D24T3nTHyllukTU4m4KsCzJfwFz407dNWk7niDTZVMXUn893_dIbxZ-WOCKgRpqupeb7ihmGbQ5C-JflP1iUScQ4tYM8EIpvm_dXvg

Build successful.

Here, I want to copy the value of Mid-access token from this file "token.txt" and would want to assign it to a variable called ttk.

The file appears to contain the required token on the first line, so open it with open() , and read the first line into a variable:

with open('somefile.txt') as f:
    ttk = next(f).replace('Mid-access token:', '').strip()

Now variable ttk will contain the token string. str.replace() removes the prefix from the line and the str.strip() is there to remove any surrounding whitespace such as the new line character from the end of the line.

Edit

It seems that the token line actually occurs towards the end of the file, always following the Mid-access token: line. Here is some code that will extract the token regardless of its location within the file:

ttk = None
with open('somefile.txt') as f:
    for line in f:
        if line.startswith('Mid-access token:'):
            ttk = next(f).strip()

print(ttk)

To get contents from document add open(token.txt, r)

To save to file use

data=myfile.read().replace("mid-acess token:" "")

Print results

print(data)

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