可以使用一维数组来读取文件并计算行数和列数。下面是一个示例代码:
def count_rows_and_columns(filename):
rows = 0
columns = 0
with open(filename, 'r') as file:
for line in file:
rows += 1
columns = max(columns, len(line.split()))
return rows, columns
filename = 'example.txt'
rows, columns = count_rows_and_columns(filename)
print(f"行数:{rows}")
print(f"列数:{columns}")
在上述代码中,我们打开文件并使用文件对象的迭代功能来逐行读取文件。通过在每个迭代中增加rows
计数器来计算行数。在每行中,我们使用split()
方法将行按空格分割为字符串列表,并使用len()
函数获取该行的列数。我们将该值与columns
变量中的当前最大列数进行比较,并使用max()
函数更新columns
。
最后,我们返回计算的行数和列数,并打印结果。请注意,该示例假设文件中的每行具有相同数量的列。