Loading subject…
Python:
Java:
Python, one line at a time:
Python, read() and readline():
Java, with Scanner:
Java, with BufferedReader:
Python:
Java:
Python:
Java:
Python:
Java:
Python:
Java:
f = open("scores.txt", "r") # read an existing filef = open("scores.txt", "w") # create or empty the filef = open("scores.txt", "a") # add to the end of the fileScanner sc = new Scanner(new File("scores.txt")); // readBufferedReader br = new BufferedReader(new FileReader("scores.txt")); // readFileWriter fw = new FileWriter("scores.txt"); // create or emptyFileWriter fa = new FileWriter("scores.txt", true); // appendwith open("scores.txt", "r") as f: for line in f: print(line.strip())f = open("scores.txt", "r")first = f.readline() # just the first linerest = f.read() # everything still leftf.close()Scanner sc = new Scanner(new File("scores.txt"));while (sc.hasNextLine()) { System.out.println(sc.nextLine());}sc.close();BufferedReader br = new BufferedReader(new FileReader("scores.txt"));String line = br.readLine();while (line != null) { System.out.println(line); line = br.readLine();}br.close();with open("scores.txt", "w") as f: # starts from empty f.write("Ada,91\n") f.write("Grace,88\n")
with open("scores.txt", "a") as f: # keeps both lines above f.write("Alan,95\n")FileWriter fw = new FileWriter("scores.txt"); // starts from emptyfw.write("Ada,91\n");fw.write("Grace,88\n");fw.close();
FileWriter fa = new FileWriter("scores.txt", true); // keeps both lines abovefa.write("Alan,95\n");fa.close();with open("scores.txt", "a") as f: f.write("Alan,95\n")# the file is closed here, automaticallytry (FileWriter fw = new FileWriter("scores.txt", true)) { fw.write("Alan,95\n");}// the file is closed here, automaticallytry: with open("scores.txt", "r") as f: print(f.read())except FileNotFoundError: print("scores.txt is missing")try (Scanner sc = new Scanner(new File("scores.txt"))) { while (sc.hasNextLine()) { System.out.println(sc.nextLine()); }} catch (FileNotFoundException e) { System.out.println("scores.txt is missing");}with open("scores.txt", "r") as source, open("top.txt", "w") as target: for line in source: name, mark = line.strip().split(",") if int(mark) >= 80: target.write(name + "," + mark + "\n")Scanner sc = new Scanner(new File("scores.txt"));FileWriter fw = new FileWriter("top.txt");
while (sc.hasNextLine()) { String[] parts = sc.nextLine().split(","); if (Integer.parseInt(parts[1]) >= 80) { fw.write(parts[0] + "," + parts[1] + "\n"); }}
sc.close();fw.close();