从文本文件中的每一行获取一个int,可以使用以下方法:
with open('file.txt', 'r') as file:
lines = file.readlines()
integers = []
for line in lines:
integer = int(line.strip())
integers.append(integer)
print(integers)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadIntsFromFile {
public static void main(String[] args) {
List<Integer> integers = new ArrayList<>();
String filePath = "file.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
integers.add(Integer.parseInt(line.trim()));
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(integers);
}
}
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
const lines = data.split('\n');
const integers = lines.map(line => parseInt(line.trim()));
console.log(integers);
});
using System;
using System.IO;
using System.Collections.Generic;
class ReadIntsFromFile
{
static void Main()
{
string filePath = "file.txt";
List<int> integers = new List<int>();
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
integers.Add(int.Parse(line.Trim()));
}
}
foreach (int integer in integers)
{
Console.WriteLine(integer);
}
}
}
以上是四种常见编程语言的示例代码,可以从文本文件中的每一行获取一个int。
领取专属 10元无门槛券
手把手带您无忧上云