英文:
How do I pull a value next to another value in a text file
问题
# 声明正确格式的日期以在文件中搜索
date_search_formatted = date_input.strftime("%m/%d/%Y")
# 打开文本文件
file = open("Invoice_doc_01.txt", "r")
# 读取文本文件
file_contents = file.read()
# 在字符串中搜索日期
index = file_contents.find(date_search_formatted)
# 如果找到日期,可以从索引位置找到对应的发票号码
if index != -1:
# 获取日期前面的文本
left_part = file_contents[:index]
# 找到最后一个逗号的位置,从而确定发票号码的起始位置
comma_index = left_part.rfind(',')
if comma_index != -1:
invoice_number = left_part[comma_index + 1:]
print("发票号码:", invoice_number)
# 关闭文本文件
file.close()
英文:
I used an excel file and equation to list a few hundred dates that a week ends on, and there is a specific invoice number that should ascociate with each date. I converted it to a txt file so the entries look like this:
1001,09/26/20,
1002,10/03/20,
1003,10/10/20,
1004,10/17/20,
1005,10/24/20,
I would like to be able to search the file for the date entry, then find the corresponding invoice number located to its left. If it is easier to search and get the value, it would be easy to change the invoice numbers to be on the right side.
This is the code I drafted to format the date into the format used in the text file, then search for it. I have no idea what to write for what happens after.
# declare the correct formatted date to search the file for
date_search_formatted = date_input.strftime("%m/%d/%Y")
# open the text file
file = open(r"Invoice_doc_01.txt", "r")
# read the text file
file.read()
# search for the string
file.find(date_search_formatted)
# save the text file
file.close()
答案1
得分: 1
使用字典:
import csv
csv_string = """1001,09/26/20,
1002,10/03/20,
1003,10/10/20,
1004,10/17/20,
1005,10/24/20,
"""
lines = csv_string.splitlines()
reader = csv.reader(lines)
inv = {}
for line in reader:
inv] = line[1]
for k, v in inv.items():
print(k, v)
# 搜索例如
if k == '1003':
print(f"Invoice no {k} from {v}")
请注意,代码部分已排除在翻译之外。
英文:
Use a dictionary:
import csv
csv_string="""1001,09/26/20,
1002,10/03/20,
1003,10/10/20,
1004,10/17/20,
1005,10/24/20,
"""
lines = csv_string.splitlines()
reader = csv.reader(lines)
inv = {}
for line in reader:
inv] = line[1]
for k, v in inv.items():
print(k, v)
# search for e.g.
if k == '1003':
print(f"Invoice no {k} from {v}")
答案2
得分: 0
如果您的文件实际上是CSV格式,您可以使用CSV读取器加载它,并从那里继续。
作为附注,当打开文件时,使用with
语句是良好的实践。
英文:
If your file is actually a CSV, you can use the csv reader to load it and continue from that.
As a sidemark, it is good practice to use the with
statement, when opening files.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论